Welcome to the React Tutorial! This guide will help you get started with React, a popular JavaScript library for building user interfaces.
Introduction
React is maintained by Facebook and is used by many large companies around the world. It allows developers to create reusable UI components and manage the state of their applications efficiently.
Installation
Before you start, make sure you have Node.js and npm installed. You can download them from nodejs.org.
To create a new React project, run the following command in your terminal:
npx create-react-app my-app
This will create a new directory called my-app
with all the necessary files and dependencies.
Basic Components
React components are the building blocks of your application. They can be class-based or function-based.
Function Components
Here's an example of a simple function component:
import React from 'react';
function Welcome() {
return <h1>Hello, world!</h1>;
}
export default Welcome;
Class Components
Class components are another way to create React components. Here's an example:
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Hello, world!</h1>;
}
}
export default Welcome;
JSX
JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you to write HTML-like code in your JavaScript files.
const element = <h1>Hello, world!</h1>;
State and Lifecycle
React components can have state and lifecycle methods. State is a way to store and update data within a component.
import React, { Component } from 'react';
class Clock extends Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
export default Clock;
Handling Events
React components can handle events just like regular HTML elements. Here's an example of a button that changes its text when clicked:
import React, { Component } from 'react';
class ClickCounter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<button onClick={this.handleClick}>
Clicked {this.state.count} times
</button>
</div>
);
}
}
export default ClickCounter;
Next Steps
Now that you've learned the basics of React, you can continue to explore more advanced topics such as hooks, context, and routing. For more information, check out our React Advanced Tutorial.
React is a powerful tool for building modern web applications. By following this tutorial, you should now have a solid foundation to start building your own React applications. Happy coding! 🚀