Creating a custom component – React fundamentals

Hi, this post contains a quick explanation of how a custom component work in React.

So, components are basically functions which return something that is “renderable” (more React elements, strings, null, numbers, etc.)

In this example we are going to reduce this DOM creating a function that help us to do this.

<div class="container">
  <div class="message">Hello World</div>
  <div class="message">Goodbye World</div>

The function need to accept an object as a parameter with children property and this function will return the React element.

 const message = props => {
      return <div className="message">{props.children}</div>

Then we can call this function in our JSX (like an expression using the { }):

<div className="container">
  {message({children: 'Hello World'})}
  {message({children: 'Goodbye World'})}

Nice, the result is:

Cool, now in the function parameter (prop) we can “destructure” that prop and get just the children property like this:

  const message = ({children}) => {
      return <div className="message">{children}</div>

When we use custom components (functions) this code made the entire app more readable and also less code is written.

By Cristina Rojas.