ReactRoot

Setting Up Your Environment

If you haven’t set up a React project yet, you can use Create React App:

bashCopy codenpx create-react-app react-root
cd react-root

Step 2: Create Basic Components

We will create two main components: TaskList and AddTask.

1. Create TaskList.js

In the src folder, create a new file called TaskList.js:

jsxCopy code// src/TaskList.js
import React from 'react';

const TaskList = ({ tasks, onDelete }) => {
  return (
    <ul>
      {tasks.map((task, index) => (
        <li key={index}>
          {task}
          <button onClick={() => onDelete(index)}>Delete</button>
        </li>
      ))}
    </ul>
  );
};

export default TaskList;

2. Create AddTask.js

Now create another file called AddTask.js:

jsxCopy code// src/AddTask.js
import React, { useState } from 'react';

const AddTask = ({ onAdd }) => {
  const [inputValue, setInputValue] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (inputValue) {
      onAdd(inputValue);
      setInputValue('');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        placeholder="Add a new task"
      />
      <button type="submit">Add</button>
    </form>
  );
};

export default AddTask;

Step 3: Main Application Component

Now, let’s integrate everything in App.js.

jsxCopy code// src/App.js
import React, { useState } from 'react';
import TaskList from './TaskList';
import AddTask from './AddTask';

const App = () => {
  const [tasks, setTasks] = useState([]);

  const addTask = (task) => {
    setTasks([...tasks, task]);
  };

  const deleteTask = (index) => {
    const newTasks = tasks.filter((_, i) => i !== index);
    setTasks(newTasks);
  };

  return (
    <div>
      <h1>ReactRoot: Task Manager</h1>
      <AddTask onAdd={addTask} />
      <TaskList tasks={tasks} onDelete={deleteTask} />
    </div>
  );
};

export default App;

Step 4: Run Your Application

Now you can start your application. In your terminal, run:

bashCopy codenpm start

Step 5: Explore and Enhance

You now have a basic React application called “ReactRoot” that allows you to manage a list of tasks. You can enhance it by adding features like:

  • Editing tasks
  • Marking tasks as complete
  • Persisting tasks in local storage

Summary

In this tutorial, you created a simple task manager app with React. You learned how to manage state, create reusable components, and handle user interactions.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *