This tutorial aims to provide a comprehensive understanding of how to build and use React Components - the building blocks of any React application. By the end of this tutorial, you should be able to create reusable components and integrate them into your application.
Components are independent, reusable pieces of code. They serve the same purpose as JavaScript functions but work in isolation and return HTML via a render function.
There are two types of components in React: functional components and class components. Functional components are just JavaScript functions. They accept properties (props) as an argument and return a React element. On the other hand, class components are ES6 classes that extend the Component class from React library.
A React component can be created using a JavaScript function or a class. Here's a simple example of a functional component:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
And here's how you can create the same component, but as a class:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
React components can be used just like regular JSX tags. They can be self-closing or can wrap other content:
<Welcome name="Sara" />
Let's create a 'Greeting' component which will display a greeting message based on the time of day.
function Greeting(props) {
const date = new Date();
const hours = date.getHours();
let timeOfDay;
if (hours < 12) {
timeOfDay = "morning";
} else if (hours >= 12 && hours < 17) {
timeOfDay = "afternoon";
} else {
timeOfDay = "night";
}
return <h1>Good {timeOfDay}, {props.name}!</h1>;
}
You can use this component in the following way:
<Greeting name="John" />
In this tutorial, we've learned about React components, how they are created, and how they can be used. We've also learned about the difference between functional and class components, and how to pass data through props.
For further learning, you can explore more complex concepts like component lifecycle, hooks, and context API. Refer to the official React documentation for more details.
Create a 'UserProfile' component that displays a user's name, email, and profile picture. The data should be passed in as props.
Create a 'Counter' component that increments a count each time a button is clicked. Use state to manage the count.
Create a 'TodoList' component. This should include an input field for adding todos, a button to add the todo to the list, and a list displaying all the todos. Use state to manage the todos.
Remember, practice is key when it comes to learning new concepts, so keep building with React!