Build reusable UI components with React.js and state management.
Learn to create reusable UI components in React.js with this step-by-step guide.
React.js is a JavaScript library for building user interfaces, emphasizing reusable components. Components are independent, reusable pieces of UI, like buttons or forms, that can manage their own state and props.
Create a new React app using Create React App:
npx create-react-app my-app
cd my-app
npm start
This sets up a development environment at http://localhost:3000
.
Functional components are JavaScript functions that return JSX. Here’s a simple component:
function Welcome(props) {
return Hello, {props.name}!
;
}
Use this component in your app:
import React from 'react';
import ReactDOM from 'react-dom';
import Welcome from './Welcome';
ReactDOM.render( , document.getElementById('root'));
Use the useState
hook to add state to functional components:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
Count: {count}
);
}
This component tracks a counter value and updates it when the button is clicked.
Let’s build a simple to-do list component:
import React, { useState } from 'react';
function TodoList() {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState('');
const addTodo = () => {
if (input.trim()) {
setTodos([...todos, input]);
setInput('');
}
};
return (
setInput(e.target.value)}
placeholder="Add a task"
/>
{todos.map((todo, index) => (
- {todo}
))}
);
}
export default TodoList;
This component allows users to add tasks to a list, using state to manage the input and task list.
Enhance the to-do list by adding features like task deletion or persistence with local storage. Explore other hooks like useEffect
for side effects.