Section 32 – Lesson 422 – Complete 2020 Web Development Bootcamp

Lesson 422 – React Components

React components allow you to split up a large file or complex web structure into smaller components.

The first component you will create is a heading component. You start by creating a function like this –

function Heading() {
  return <h1>My Favourite Foods</h1>;
}

You then refactor the ReactDOM.render() code to insert the Heading function like this –

ReactDOM.render(
  <div>
    <Heading />
    <ul>
      <li>Bacon</li>
      <li>Jamon</li>
      <li>Noodles</li>
    </ul>
  </div>,
  document.getElementById("root")
);

The next step is to create a separate file called “Heading.jsx” and then move our Heading function to that file. The Heading.jsx is then imported to the index.js file.

The Heading.jsx file has to import react in order to function. The Heading.jsx including the import React command now looks like this –

import React from "react";

function Heading() {
  return <h1>My Favourite Foods</h1>;
}

In order for the Heading function to be exported, this line of code has to be added at the bottom of the Heading.jsx file –

export default Heading;

The Heading.jsx file now looks like this –

import React from "react";

function Heading() {
  return <h1>My Favourite Foods</h1>;
}

export default Heading;

The last step is to import the Heading into the index.js file using this code –

import Heading from "./Heading";

The refactored index.js file now looks like this –

import React from "react";
import ReactDOM from "react-dom";
import Heading from "./Heading";

ReactDOM.render(
  <div>
    <Heading />
    <ul>
      <li>Bacon</li>
      <li>Jamon</li>
      <li>Noodles</li>
    </ul>
  </div>,
  document.getElementById("root")
);

The challenge in this lesson is to refactor the code to use a React component for the list element.

In order to complete this challenge, you first create a new List.jsx file containing the following code –

import React from "react";

function List() {
 return <ul>
    <li>Bacon</li>
    <li>Jamon</li>
    <li>Noodles</li>
  </ul>;
}
export default List;

You then import the List.jsx file into the index.js file. The refactored index.js file looks like this –

import React from "react";
import ReactDOM from "react-dom";
import Heading from "./Heading";
import List from "./List";

ReactDOM.render(
  <div>
    <Heading />
    <List />
    
  </div>,
  document.getElementById("root")
);