bradtraversy / react-crash-2021

Task tracking application from the React crash course
1.36k stars 1.72k forks source link

Crash when using React Router v6 [solution] #21

Open vbrg opened 2 years ago

vbrg commented 2 years ago

Tried doing this tutorial but used React Router v6 instead of v5 and then I got this error Error: A <Route> is only ever to be used as the child of <Routes> element So there's some changes and so I made App.js like this instead

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

//*code*

  return (
    <Router>
      <div className="container">
        <Header
          onAdd={() => setShowAddTask(!showAddTask)}
          showAdd={showAddTask}
        />
        <Routes>
          <Route
            path="/"
            exact
            element={
              <Home
                showAddTask={showAddTask}
                addTask={addTask}
                tasks={tasks}
                Tasks={Tasks}
                toggleReminder={toggleReminder}
                deleteTask={deleteTask}
                AddTask={AddTask}
              />
            }
          />
          <Route path="/about" element={<About />} />
        </Routes>
        <Footer />
      </div>
    </Router>
  );
}

export default App;

and defined a new file Home.js like this

function Home({ showAddTask, addTask, tasks, Tasks, toggleReminder, deleteTask, AddTask }) {
  return (
    <div>
      {showAddTask && <AddTask onAdd={addTask} />}
      {tasks.length > 0 ? (
        <Tasks tasks={tasks} onDelete={deleteTask} onToggle={toggleReminder} />
      ) : (
        "No Tasks To Show"
      )}
    </div>
  );
}

export default Home;

Probably stupid. Don't know much about things web-related.

MDPATH commented 2 years ago

Thanks a lot, I am very new to React and was struggling with this when I followed the course and wasted so much time trying to figure it out. This worked great

jrvgon commented 2 years ago

I have an issue where the tasks dont show after starting the app.

liyaquath-code commented 2 years ago

I found a better solution.

  1. Import Routes from 'react-router-dom'

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'

  1. Change component={About} to element={<About />}
  2. Change the route with render method with the following code
<Route path='/' exact element={
                        <>
                            {showAddTask && <AddTask onAdd={addTask} />}
                            {tasks.length > 0 ?
                                <Tasks tasks={tasks}
                                    onDelete={deleteTask}
                                    onToggle={toggleReminder}
                                />
                                : <p>No Tasks available</p>}
                        </>
                    } />