DEV Community

Cover image for Project 17 of 100 - React Child Generator
James Hubert
James Hubert

Posted on

Project 17 of 100 - React Child Generator

Hey! I'm on a mission to make 100 React.js projects in 100 days starting October 31, 2020 and ending February 7th, 2021. Please follow my dev.to profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!

Link to today's deployed app: link
Link to the repo: github

I've been quite sick for the last week and a half, hence my gap in projects for my 100 days 100 projects campaign.

Yesterday was my first day feeling back to almost normal so I made a goofy little React app dedicated to exploring the concept of children in React.

props.children

Now, the idea with children is that any number of JSX elements can be given as the inner HTML within another JSX element. Simply make sure you use {props.children} within the Component, like so:

function MyComponent(props) {
  return (
    <div>
      <p>My little component here...</p>
    </div>
  )
}

function App() {
  return (
    <MyComponent>
      <h2>A little jsx element</h2>
      <h2>Another little jsx element</h2>
    </MyComponent>
  )
}
Enter fullscreen mode Exit fullscreen mode

Now all we need to do to to make sure the new JSX is included within the MyComponent element is elicit props.children like so:

function MyComponent(props) {
  return (
    <div>
      <p>My little component here...</p>
      {props.children}
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Application

For my application I had a form where users could prototype a new shape. When the user is happy with the shape they submit the form and the shape is added to an array of child components.

We do this by using {props.children} within the CreatedElContainer component. We can pass as many child elements as we want to the component! And in any configuration.

I can't understate how useful it is to be able to pass any number of custom child elements to a custom component. This allows us to re-use components as many times as we want and still fill them with unique elements. Pretty cool!

That's it for today's project. See you tomorrow.

Top comments (2)

Collapse
 
jaagrav profile image
Jaagrav • Edited

Great Article!
Suppose now, I have an element, what I want to do is generate an element inside the previous elements.

Basically like this,
-------element 1
---element 2---|
-element 3-----|

...and so on.

How'd you do that with React?

Collapse
 
jwhubert91 profile image
James Hubert

Thanks Jaagrav :)
I'm not totally sure what you mean- but you could be talking about Higher Order Components? This allows you to wrap a component in another component.