Solution for React: Render a Class Component to the DOM lesson

This lesson definitely needs a solution. The sample code in the hint section is not explained properly. This is a solution I wrote for React: Render a Class Component to the DOM lesson.

Link to the lesson: https://www.freecodecamp.org/learn/front-end-libraries/react/render-a-class-component-to-the-dom
Code explanation:

  • Add the id to the div.

  • Render Fruits component exactly after the h1.

  • Follow up that with Vegetables component.

  • Render both Fruits and Vegetables component right after those.

  • Pay attention to the document.getElementById('node-id') as you want to render TypesOfFood component itself. ReactDOM.render(<ComponentToRender />, targetNode) Here targetNode is the div but you should call it, by getting it’s element id.

class TypesOfFood extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div id='challenge-node'>
        <h1>Types of Food:</h1>
        {/* change code below this line */}
           <Fruits/>
             <Vegetables/>
             ReactDOM.render(<Fruits/>, h1)
             ReactDOM.render(<Vegetables/>, h1)
        {/* change code above this line */}
      </div>
    );
  }
};

// change code below this line
ReactDOM.render(<TypesOfFood/>, document.getElementById('challenge-node'));

Please format your code properly.

ok sure, How should I revise it? Should I add more details?

Use proper indentation. You can use the format option in the fCC challenge code editor (Ctrl + Alt + F).

I could not find FCC format option in the search box.
I did some changes, hopefully I did it right.

This isn’t correct.

  1. Why are there 3 ReactDOM.render calls? You should just use the components.

  2. You are not asked to add the challenge-node id to the div.

Really your code should probably not be passing the tests, but it does.

Solution example:

class TypesOfFood extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>Types of Food:</h1>
        {/* change code below this line */}
        <Fruits />
        <Vegetables />
        {/* change code above this line */}
      </div>
    );
  }
};

// change code below this line
ReactDOM.render(<TypesOfFood />, document.getElementById('challenge-node'))
1 Like

ok, Thank you for the correction.

I just realized this challenge already has a solution on the hints page and an explanation.

I will close this thread as I don’t think anything else is needed. But thank you for contributing non the less.

1 Like