Https://www.freecodecamp.org/learn/front-end-libraries/react/create-a-component-with-composition

Tell us what’s happening:
Describe your issue in detail here.
Why do we have to split our HTML code into two different components if we can write it as a single component?

  **Your code so far**

const ChildComponent = () => {
return (
  <div>
    <p>I am the child</p>
  </div>
);
};

class ParentComponent extends React.Component {
constructor(props) {
  super(props);
}
render() {
  return (
    <div>
      <h1>I am the parent</h1>
      { /* Change code below this line */ }
        <ChildComponent />

      { /* Change code above this line */ }
    </div>
  );
}
};
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36

Challenge: Create a Component with Composition

Link to the challenge:

with short code like this it is not very obvious why. It is even tedious since you have written more code than necessary, but off the top of my head:

  • You have a section in your component that is long and functionally independent
  • You are repeating blocks of code in your component
  • you want to split the different components into different .js files for organization/clarity

Those are all good reasons why sometimes we make something a child component instead of nesting it in the parent.

Basically for composition and reuse. This might not make a lot of sense just yet but if you keep learning about React it will at some point. The key is for you to learn and use React for long enough to see it in action.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.