Nested Components

In React, we can nest components inside within one another. This helps in creating more complex User Interfaces. The components that are nested inside parent components are called child components. Import and Export keywords facilitate nesting of the components.

  • Export - This keyword is used to export a particular module or file and use it in another module.

  • Import - This keyword is used to import a particular module or file and use it in the existing module.

    • Importing named values allows the user to import multiple objects from a file.

Create a Floor Plan Using Nested Components

Creating a Floor Plan is a great way to understand and apply our knowledge of React components. Before starting on this activity, create an account at Code Sandbox and create a new React project.

Setting Up Your Files

The React template in Code Sandbox will automatically generate the following files and codes for you:

Let's ignore what's inside these boilerplate code first and start thinking about what files we need to create for our Floor Plan.

Based on the diagram above, these are the various components we need to create:

  • FloorPlan

  • Bedroom1

  • Bedroom2

  • Bedroom3

  • FullBath

  • HalfBath

  • Kitchen

  • Oven

  • Sink

  • LivingRoom

You will notice that the naming for the components are in UpperCamelCase, for example, a <SomeComponent> component's file would be named SomeComponent.js, and each component has its own file, like FullBath and HalfBath instead of just Bath.

To visualise each component's wrapping, add the following inside your styes.css.

styles.css
div {
  border: 1px solid grey;
  margin: 5px;
  padding: 5px;
}

A border should appear around the div. This will help us identify whether we have structured our components correctly:

Create Bedroom1 Component

  1. Create a variable called Bedroom1 returning a <h1 classname>

  2. Export the component from it's module

Import Bedroom1 Component into FloorPlan

  1. Use import to import the Bedroom1 component

  2. Create a variable called Floorplan returning a <div classname>

  3. Export the component from it's module

Import React and FloorPlan Component into App

  1. Use import to import the FloorPlan component

  2. Remove the <h1> and <h2> from the <div section> and replace it with <FloorPlan />.

Now your bedroom should appear in your browser!

Create the rest of the FloorPlan components

Now that you know how to import and export the components, create the rest of the FloorPlan components before referencing the solution below:

! Note: You will need to adjust your CSS styling so it will look like the one in the diagram

Solution to Bonus: https://codesandbox.io/s/react-floor-plan-p77gf?file=/src/styles.css

🏆CODING TIME COMPLETED

Last updated