Here’s a 20-minute React tutorial designed for beginners. React is a popular JavaScript library for building user interfaces and single-page applications (SPAs). In this tutorial, you will learn the basic concepts of React and build a simple component-based application. Let’s dive in!
1. What is React? (2 minutes)¶
- React is a JavaScript library for building fast and interactive UIs, developed by Facebook.
- React uses components, which are reusable building blocks, to define UIs.
- It updates only the parts of the DOM that need changes, improving performance.
2. Setting Up React (3 minutes)¶
Option 1: Using CodeSandbox (No Setup)¶
- Visit CodeSandbox, and select the React template to instantly start coding.
Option 2: Local Setup Using Create React App¶
- Make sure you have Node.js installed.
- Run the following command to create a new React app:
bash npx create-react-app my-app - Navigate into the project directory:
bash cd my-app - Start the development server:
bash npm startThis opens your app in the browser athttp://localhost:3000.
3. React Components (4 minutes)¶
A component in React is a JavaScript function or class that returns JSX (JavaScript XML), which looks like HTML but is more powerful.
Functional Component¶
- Create a new component:
js function Welcome() { return <h1>Hello, React!</h1>; } - Use this component in your main
App.js: ```js import React from 'react'; import Welcome from './Welcome';
function App() { return (
export default App; ```
React re-renders components when the data (props or state) changes.
4. JSX: JavaScript Syntax Extension (3 minutes)¶
JSX is a syntax extension that allows you to write HTML-like code inside JavaScript.
Example JSX¶
function App() {
return (
<div>
<h1>Welcome to React!</h1>
<p>This is JSX.</p>
</div>
);
}
-
JSX can include expressions wrapped in curly braces (
{}):js const name = 'John'; return <h1>Hello, {name}</h1>; // Outputs: Hello, John -
You can also use JavaScript functions and calculations inside JSX:
js const num1 = 5; const num2 = 10; return <p>Sum: {num1 + num2}</p>; // Outputs: Sum: 15
5. Props: Passing Data Between Components (3 minutes)¶
Props (short for properties) are used to pass data from one component to another.
Example¶
- Modify the
Welcomecomponent to accept anameprop:js function Welcome(props) { return <h1>Hello, {props.name}!</h1>; } - Use it in the
Appcomponent:js function App() { return ( <div> <Welcome name="Alice" /> <Welcome name="Bob" /> </div> ); }This renders:
Hello, Alice!
Hello, Bob!
Props are read-only, meaning the child component cannot modify them.
6. State: Managing Component Data (3 minutes)¶
State is used to manage data that changes over time. When the state changes, the component re-renders.
Example Using useState Hook¶
- Import the
useStatehook:js import React, { useState } from 'react'; -
Add state to the component: ```js function Counter() { const [count, setCount] = useState(0);
return (
); }Count: {count}
3. Use the `Counter` component in `App.js`:js function App() { return (); } ``` -
useStatereturns the current value (count) and a function (setCount) to update it. - Clicking the button increments the counter, and React automatically updates the UI.
7. Handling Events (2 minutes)¶
React allows you to handle DOM events such as clicks, form submissions, and more.
Example: Handling Click Events¶
function Button() {
function handleClick() {
alert('Button clicked!');
}
return <button onClick={handleClick}>Click Me</button>;
}
- The
onClickattribute is used to attach an event handler to the button.
Example: Handling Form Submissions¶
function Form() {
function handleSubmit(event) {
event.preventDefault();
alert('Form submitted!');
}
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Enter something" />
<button type="submit">Submit</button>
</form>
);
}
8. Conditional Rendering (2 minutes)¶
You can conditionally render components or elements based on certain conditions.
Example¶
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign in.</h1>;
}
In this example, the greeting will display different messages depending on whether the user is logged in.
9. Lists and Keys (2 minutes)¶
React can render lists of items dynamically. It requires a unique key for each list item to efficiently track and update the list.
Example¶
function ItemList() {
const items = ['Apple', 'Banana', 'Cherry'];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
- The
keyprop helps React identify which items have changed, been added, or removed.
10. Final Tips (1 minute)¶
- React Developer Tools: Install the React DevTools browser extension to inspect React components and state in the browser.
- Component Hierarchy: Think in terms of small, reusable components.
- Learn More: The React documentation is the best place to explore advanced topics.
With this basic understanding of React, you’re now ready to start building simple apps!