×
  • React – The Complete Guide (incl. React Router 4 & Redux)

  • 10 – Outputting Dynamic Content

    Lesson List

    In the last lesson, we see the duplicating of the component. so let’s dive into our putting some dynamic content in React.
    This far we always hardcoded some HTML elements and some text in between.

    Dynamic Content in JSX

    Let’s say <p> I am a Person and I am x year old!</p> but x should actually be a random number, and we can simply do that. We can replace x with a random number.

    src/Person/Person.js
    
    import React from 'react';
    const person = () => {
    	return <p> I am a Person and i am Math.floor(Math.random() * 30) year old!</p>;
    };
    export default person;
    

    If we output the tat code we see that just text is been outputed instade of number. this makes sense how would React know to execuate Math.floor(Math.random() * 30) as javascript. If we have some dynamic content in our JSX part which we want to run as javascript code and not interpret as text.
    For that we have to wrap into single curly braces i.e { /* Javascript code */ }, so let’s do that

    src/Person/Person.js
    
    import React from 'react';
    const person = () => {
    	return <p> I am a Person and i am {Math.floor(Math.random() * 30)} year old!</p>;
    };
    export default person;
    

    Now If you save and see in the browser you get the random numbers. Everytime you reload it gets the random number.

    Note:
    This is super important, As we see that we can output the dynamic content as part of our JSX content. We can’t define javascript class in there or anything like that. We can execute one line expressions, Short simple expressions like simple calculations or function calls.
    We will see the functions calls in event handlers.

    Now we are able to output the dynamic content. Why don’t we take it to the next level and make our component more dynamic? so that we can leave outputting some generic content like a person and a random number and instead do something else pass some configuration from the src/App.js file. Maybe some HTML attribute we passed to person to configure what we want the output for each usage of <Person /> component. will see that in the next lesson.

    React introduction
    React Component
    Dynamic Content
  • We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
    Accept