Building a Simple, Reusable React Component

Once the project is created. Go to the App.js file and change the existing code with this snippet:

Here, there is a <div> element that has some text inside it. If I want to replicate it, I will have to write the same div element again. What we can instead do is extract the div element inside a variable, and write that element directly in my app’s JSX.

If you run yarn start command, you will see that the app renders the text the same way in both cases.

What if I want to render some other kind of text? Or if I want to render two different texts?

To do so, I am going to make some changes to the helloWorld variable.

First, I have renamed the variable as message . I am then passing props as an argument to this variable. Note that I am using ES6 arrow function to do this.

props is an object that has a msg property in it. Inside the App component, I am replacing the {helloWorld} with {message} . Inside this message variable, I am defining the msg prop with some text.

I’ve now created a simple, re-usable React component. I have taken some JSX, wrapped it inside a function, and made a function call to render some text.

But function calls don’t really compose as well as JSX does. It would be better to turn these function calls into JSX. So let’s start out with React.createElement and see how we can convert into JSX. A great thing about React.createElement is that can take a string and a function to indicate what element we want to render.

It will pass the props to the function, and that function presumably will some more elements. Here, the message function is rendering a <div> .

But this looks way too complicated. Let’s simplify things like this:

Here, I am changing my message function to Message , changing the function into a component. By doing so, I can use it as a self-closing element inside the App component as shown in the above code snippet.

If I change the msg prop to children prop, React will still render the exact same thing. I can even put one Message element inside another Message element.

class App extends Component {

render() {

return (

<Message>

Hello World

<Message>Reusable Components</Message>

</Message>

);

}

}