Hello, in this tutorial, we'll talk about components.
Hello, in this tutorial, we'll talk about components.
In React Project Structure, you saw that there is this code snippet in index.js.
A React application generally based on the concept of components - where you have a root (main) component and in it, can contain other components.
<App /> is a component that is generated when we created the React application via the command line. It is what you see when you launch the server and viewed the application on the browser using npm run start.
The Basic Structure of a Component
If we look into the App.js file, it contains the code for the App component.
B) The component logic and markup used to render the component onto the page.
export default App;
With this knowledge, let's create our own component and see how it works.
Creating our First Component
Step 1:
To begin, create a folder inside the src directory call components. This is optional but we're doing it to be more organized and keeping all the components in a folder call components.
Step 2:
Now create a new file call MyFirstComponent.js inside the components folder. Make sure to have the "js" extension.
Step 3:
(Optional)
If you are using React version 18+, you will not need to import React into the component. But if you are using a lower version of React, you need to import it like this at the top of the component file.
import React from 'react';
You can find out what version of React you are using in the package.json file inside the dependencies object.
Since I am using version 18 of React, I do not need to import it.
Step 4:
Create a function call MyFirstComponent.
Step 5:
export default MyFirstComponent;
We're finish, we have our first component. The next step is to add it to the page.
Using the Component
Now that we have a component, we can add it to a component.
Step 2:
import MyFirstComponent from './components/MyFirstComponent';
In this line, we want to import MyFirstComponent from the MyFirstComponent.js file in the components directory.
The "./" means the current directory.
Step3:
Now we can add the component inside like this:
Now save ALL the files and launch the app.
You should see nothing. That is expected since we did not add anything inside our component.
If you look at the App component function, you can see that it returns some HTML code.
Since our component is not returning anything, we get nothing.
Return HTML
Step 4:
That's all for this tutorial. You made your first component!