Nested Components
Last updated
Last updated
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.
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.
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.
A border should appear around the div. This will help us identify whether we have structured our components correctly:
Create a variable called Bedroom1
returning a <h1 classname>
Export the component from it's module
Use import to import the Bedroom1
component
Create a variable called Floorplan
returning a <div classname>
Export the component from it's module
Use import to import the FloorPlan
component
Remove the <h1>
and <h2>
from the <div section> and replace it with <FloorPlan />
.
Now your bedroom should appear in your browser!
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