ReactJS Tutorial
ReactJS is a JavaScript library used to build dynamic user interfaces. It is component-based and declarative, making it efficient for creating large, complex applications. This tutorial covers the basics of setting up React, building components, and managing state.
1. Setting Up a React Projectβ
Using create-react-appβ
create-react-app is a command-line tool that sets up a React project with all necessary configurations.
-
Install
create-react-appglobally (if not installed):npm install -g create-react-app -
Create a new React project:
npx create-react-app my-app
cd my-app -
Start the development server:
npm start
This will start the app at http://localhost:3000.
2. React Componentsβ
Components are the building blocks of a React app. Each component represents a part of the UI.
Functional Componentβ
import React from 'react';
function Greeting() {
return <h1>Hello, World!</h1>;
}
export default Greeting;
Class Componentβ
import React, { Component } from 'react';
class Greeting extends Component {
render() {
return <h1>Hello, World!</h1>;
}
}
export default Greeting;
3. JSX (JavaScript XML)β
JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you to write HTML-like code within JavaScript.
Exampleβ
const element = <h1>Hello, World!</h1>;
Notes:
- JSX must have a single parent element.
- Use curly braces
{}to embed JavaScript expressions.
4. Props (Properties)β
Props are used to pass data from a parent component to a child component.
Exampleβ
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Welcome name="Alice" />;
}
In this example, "Alice" is passed as a prop to Welcome.
5. Stateβ
State is a way to store dynamic data within a component. It is managed within the component and can change over time.
Example using useState Hookβ
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Class Component with Stateβ
import React, { Component } from 'react';
class Counter extends Component {
state = { count: 0 };
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
6. Handling Eventsβ
Events in React are handled similarly to JavaScript, but they follow camelCase naming, and you pass a function reference instead of a string.
Exampleβ
function Button() {
function handleClick() {
alert('Button clicked!');
}
return <button onClick={handleClick}>Click me</button>;
}
7. Conditional Renderingβ
React allows you to conditionally render components or elements.
Exampleβ
function Message({ isLoggedIn }) {
return isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>;
}
8. Lists and Keysβ
When rendering lists, each list item should have a unique key to help React identify changes.
Exampleβ
function NameList() {
const names = ['Alice', 'Bob', 'Charlie'];
return (
<ul>
{names.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
);
}
9. Lifecycle Methods (Class Components)β
Lifecycle methods are functions that get called at different stages of a componentβs life. They only work in class components.
- componentDidMount: Called after the component is added to the DOM.
- componentDidUpdate: Called after the component is updated.
- componentWillUnmount: Called before the component is removed.
10. React Hooksβ
Hooks allow you to use state and lifecycle features in functional components.
Common Hooksβ
- useState: Adds state to functional components.
- useEffect: Runs side effects (e.g., data fetching, subscriptions).
Example of useEffectβ
import React, { useState, useEffect } from 'react';
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => setCount((prev) => prev + 1), 1000);
return () => clearInterval(timer); // Cleanup on unmount
}, []);
return <h1>Timer: {count}</h1>;
}
Summaryβ
This tutorial covered the basics of ReactJS:
- Setting up a project with
create-react-app. - Building components and managing state with hooks.
- Handling props, events, and conditional rendering.
- Understanding component lifecycle and React Hooks.
React is a powerful library that simplifies the process of building dynamic, responsive user interfaces.
Content Reviewβ
The content in this repository has been reviewed by chevp. Chevp is dedicated to ensuring that the information provided is accurate, relevant, and up-to-date, helping users to learn and implement programming skills effectively.
About the Reviewerβ
For more insights and contributions, visit chevp's GitHub profile: chevp's GitHub Profile.