Placing a component
Your React component turns to a new tag.
In the previous lesson we learned that React is a library that helps us create a UI components. We also learned that to create a component in React, we need to create a function that returns how that component looks like. React components are reusable ui, which can be placed on desired places in the screen (can also be placed multiple times in different places). When you create a component, you can place it in the screen by using its function name as a tag inside another React component.
Let's give a simple example, in the following example we have two components that are located in two different files:
App.js
- This is the component that represents the entire screen.Login.js
- This is a component that represents the login form (same one we created in the previous lesson).
Few things to note in the following example:
Component tree
React application is made from a tree of components, usually the root of the component represents the entire application, or the root represents the current screen from the web application that we are visiting. This means that a screen like this:
We can create this screen with the following components:
When we create a React application we are building a tree of components (this is the popular way of creating a web application today, and this approach is the common way in other popular frameworks as well).
Splitting files
It's common to split your application to multiple files, and you will often place a component in a seperate file (like in this example where we had 2 components splitted to 2 files: App.js
and Login.js
).
When splitting files we use ES6 Modules. so one syntax is to use export default
:
Or you can use export
Few things to note here:
- If you place a component in a seperate file, you need to import it in the file that you want to use it.
- The name of the component is the name of the function.
- That name has to be in PascalCase (camelCase but with the first letter capitalized, otherwise React will not recognize it as a component - but a tag name).
Exercise - component tree
In this exercise we will create the following component tree:
Where the focus is to simply place those components, and not on the styling of those components which we will cover in the next lesson. You can write the code right here in the site:
Solution
And here is the solution for the exercise:
Summary
In this lesson we learned that a React web site is simply a component tree, a component can be placed in seperate file, and it can be imported in other components and placed as a tag.