Introduction to ReactJS
ReactJS is a popular front-end library used for building user interfaces and single-page applications. In this article, we will explore the basics of ReactJS and create a complete project from scratch.
Setting Up the Project
To start with, we need to have Node.js and a code editor of our choice installed on our machine. In this case, we will use Visual Studio Code. We create a new folder called "react-youtube" and open it directly in Visual Studio Code.
We then open the terminal directly from Visual Studio Code and use Vite, which is faster than Create React App, to launch the following commands: npm create vite@latest my-react-app
. This will create a new React project.
Creating the First Component
We start by creating a new component called WelcomeMessage.jsx
. We create a folder called components
where we will insert all our components. In the WelcomeMessage.jsx
file, we export a function that returns a piece of JSX.
We then go to our App.jsx
file and import the WelcomeMessage
component. We call the WelcomeMessage
component and pass a message
prop to it.
Passing Props to Components
We introduce the concept of props, which allows us to pass different parameters to the same component. We pass a message
prop to the WelcomeMessage
component and use it to display a dynamic message.
Creating a Counter Component
We create a new component called Counter.jsx
and use the useState
hook to create a state variable count
. We then use the setCount
function to increment the count
variable when the button is clicked.
Using the useState Hook
We introduce the useState
hook, which allows us to create a state variable and a function to update it. We use the useState
hook to create a state variable count
and a function setCount
to update it.
Fetching Data from an API
We introduce the useEffect
hook, which allows us to fetch data from an API when the component is mounted. We use the useEffect
hook to fetch data from the Random User API and display the user's name and image.
Conclusion
In conclusion, we have learned how to create a complete React project from scratch. We have learned how to create components, pass props to components, use the useState
hook, and fetch data from an API using the useEffect
hook.
As a final project, we create a to-do list component that allows users to add and remove tasks. We use the useState
hook to create a state variable tasks
and a function setTasks
to update it.
I hope this article has been useful to you. If you have any questions or want to learn more about React, please leave a comment below.