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.
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.
<p> I am a Person and I am x year old!</p>
x
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
Math.floor(Math.random() * 30)
{ /* Javascript code */ }
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.
class
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.
<Person />