Let’s create a project to print “Hello, world!” with React, you’ll need to create a new React project and write some JavaScript code to render the message to the page. Here’s how you can do that:
- First install React JS : Follow this tutorial
- Open the “my-app” directory in your code editor and navigate to the “src” directory.
- Open the “my-app” directory in your code editor and navigate to the “src” directory.
- Open the “App.js” file and replace the existing code with the following:
import React, { useState } from 'react';
function App() {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
setTodos([...todos, input]);
setInput('');
};
return (
<div>
<h1>Todo App</h1>
<form onSubmit={handleSubmit}>
<input value={input} onChange={(e) => setInput(e.target.value)} />
<button type="submit">Add Todo</button>
</form>
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
</div>
);
}
export default App;
- This code defines a React component called “App” that manages the state and behavior of the todo app. It uses the “useState” hook from the “react” package to create two state variables: “todos” and “input”. The “todos” variable is an array of todo items, and the “input” variable is the current value of the input field where the user can add new todo items.
- The “App” component includes a form with an input field and a button. When the user submits the form, the “handleSubmit” function is called, which adds the current value of the input field to the “todos” array and clears the input field.
- The “App” component also includes a list that displays all the todo items in the “todos” array. Each todo item is rendered as a list item in the “ul” element.
- To start the development server, navigate to the “my-app” directory in a terminal window and run the following command:
npm start
- This will start the development server and automatically open a new tab in your default web browser with the address http://localhost:3000. You should see the todo app on the page, and you should be able to add new todo items and see them appear in the list.
- To stop the development server, go back to the