Building a Simple App
Key Concepts
- Setting Up a React Project
- Creating Components
- State Management
- Props
- Event Handling
- Conditional Rendering
- Lists and Keys
- Forms and Input Handling
- Component Lifecycle
- Styling Components
- Routing
- Fetching Data
- Error Handling
- Testing
- Deployment
- Best Practices
Setting Up a React Project
To start building a simple React app, you need to set up a new React project using Create React App (CRA). Run the following command:
npx create-react-app my-app
This command creates a new directory named "my-app" with a basic React project structure.
Creating Components
Components are the building blocks of a React application. They are reusable and can be composed to create complex UIs. To create a component, define a function or class that returns JSX.
Example:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
State Management
State is a built-in object in React that stores data that can change over time. Use the useState
hook to add state to functional components.
Example:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
Props
Props (short for properties) are used to pass data from one component to another. They are read-only and help in making components reusable.
Example:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } function App() { return ( <div> <Welcome name="Alice" /> <Welcome name="Bob" /> </div> ); }
Event Handling
Event handling in React is similar to handling events on DOM elements. Use camelCase for event names and pass a function as the event handler.
Example:
function Button() { function handleClick() { alert('Button clicked!'); } return ( <button onClick={handleClick}> Click me </button> ); }
Conditional Rendering
Conditional rendering allows you to render different components or elements based on certain conditions. Use conditional operators or ternary operators for this purpose.
Example:
function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return <h1>Welcome back!</h1>; } return <h1>Please sign up.</h1>; }
Lists and Keys
Lists in React are created by mapping over an array and returning a list of elements. Each element in the list should have a unique key to help React identify which items have changed.
Example:
function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => <li key={number.toString()}> {number} </li> ); return ( <ul>{listItems}</ul> ); }
Forms and Input Handling
Forms in React require handling user input and managing form state. Use controlled components where form data is handled by the React component.
Example:
function NameForm() { const [name, setName] = useState(''); function handleChange(event) { setName(event.target.value); } function handleSubmit(event) { alert('A name was submitted: ' + name); event.preventDefault(); } return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" value={name} onChange={handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); }
Component Lifecycle
The component lifecycle consists of several phases: mounting, updating, and unmounting. Use lifecycle methods or hooks like useEffect
to perform actions at specific points in a component's lifecycle.
Example:
function Clock() { const [date, setDate] = useState(new Date()); useEffect(() => { const timerID = setInterval(() => tick(), 1000); return () => { clearInterval(timerID); }; }, []); function tick() { setDate(new Date()); } return ( <div> <h1>Hello, world!</h1> <h2>It is {date.toLocaleTimeString()}.</h2> </div> ); }
Styling Components
Styling in React can be done using inline styles, CSS modules, or CSS-in-JS libraries like styled-components. Choose the method that best fits your project.
Example:
const styles = { color: 'blue', fontSize: '16px', }; function Welcome(props) { return <h1 style={styles}>Hello, {props.name}</h1>; }
Routing
Routing allows you to create a multi-page application within a single-page application. Use React Router to handle routing in your React app.
Example:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; function App() { return ( <Router> <Switch> <Route path="/about"> <About /> </Route> <Route path="/"> <Home /> </Route> </Switch> </Router> ); }
Fetching Data
Fetching data in React can be done using the Fetch API or libraries like Axios. Use the useEffect
hook to fetch data when the component mounts.
Example:
function UserProfile() { const [user, setUser] = useState(null); useEffect(() => { fetch('https://api.example.com/user/1') .then(response => response.json()) .then(data => setUser(data)); }, []); if (!user) { return <div>Loading...</div>; } return ( <div> <h1>{user.name}</h1> <p>Email: {user.email}</p> </div> ); }
Error Handling
Error handling in React can be done using try-catch blocks for synchronous code and error boundaries for handling errors in components.
Example:
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
Testing
Testing in React can be done using libraries like Jest and React Testing Library. Write unit tests and integration tests to ensure your components work as expected.
Example:
import { render, screen } from '@testing-library/react'; import App from './App'; test('renders learn react link', () => { render(<App />); const linkElement = screen.getByText(/learn react/i); expect(linkElement).toBeInTheDocument(); });
Deployment
Deployment involves building your React app for production and hosting it on a server. Use the npm run build
command to create a production build and deploy it using services like Netlify, Vercel, or GitHub Pages.
Example:
npm run build
Best Practices
Best practices for building a simple React app include:
- Keep components small and focused
- Use functional components with hooks
- Leverage state and props effectively
- Write tests for your components
- Optimize performance by avoiding unnecessary re-renders
Analogies
Think of building a React app as constructing a house. Components are like rooms, each with its own purpose. State is like the furniture and decorations inside the rooms, which can change over time. Props are like the instructions given to the builders to construct each room. Event handling is like the switches and buttons that control the lights and appliances. Conditional rendering is like deciding whether to open or close the curtains based on the time of day. Lists and keys are like the shelves in a library, where each book (item) has a unique identifier. Forms and input handling are like the kitchen, where ingredients (input) are processed into a meal (output). The component lifecycle is like the stages of a person's life, from birth (mounting) to death (unmounting). Styling is like the paint and wallpaper that make the house look beautiful. Routing is like the different paths you can take to navigate through the house. Fetching data is like ordering groceries online and having them delivered to your doorstep. Error handling is like having a first aid kit ready for any accidents. Testing is like having a home inspection to ensure everything is working correctly. Deployment is like moving into your new house and inviting guests over.