1

Everything is working quite fine and I have set the links to the pages. The Problem is when I click on a link on the Navbar, the URL changes but page doesn't render. However, the page renders when refreshed manually. What should I do to make that work properly?

Here is the code :

import './App.css';
import Header from './MyComponents/Header';
import { Todos } from './MyComponents/Todos';
import { Footer } from './MyComponents/Footer';
import { AddToDo } from './MyComponents/AddToDo';
import { About } from './MyComponents/About';
import React, { useState, useEffect } from 'react';
import { BrowserRouter, Switch, Route } from "react-router-dom";

function App() {
  let initTodo;
  if (localStorage.getItem("todos") === null) {
    initTodo = [];
  } else {
    initTodo = JSON.parse(localStorage.getItem("todos"));
  }

  const onDelete = (todo) => {
    setTodos(todos.filter((e) => {
      return e!==todo;
    }));
    localStorage.setItem("todos", JSON.stringify(todos));
  }

  const addTodo = (title, desc) => {
    let sno;
    if (todos.length == 0) {
      sno = 0;
    } else {
      sno = todos[todos.length-1].sno + 1;
    }

    const myTodo = {
      sno: sno,
      title: title,
      desc: desc,
    };

    setTodos([...todos, myTodo]);
  }

  const [todos, setTodos] = useState(initTodo);

  useEffect(() => {
    localStorage.setItem("todos", JSON.stringify(todos));}, [todos])

  return (
    <>
      <BrowserRouter>
        <Header title="MyTodosList" searchBar={true} />
        <Switch>
          <Route
            exact
            path="/"
            render={() => {
              return (
                <>
                  <AddToDo addTodo={addTodo} />
                  <Todos todos={todos} onDelete={onDelete} />
                </>
              )}
            }
          />
          <Route exact path='/about' component={About} />
        </Switch>
        <Footer />
      </BrowserRouter>
    </>
  );
}

export default App;
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • What versions of `react` and `react-router-dom` are installed? If you are using React 18 does this help answer your question? https://stackoverflow.com/a/71833424/8690857 – Drew Reese Aug 03 '22 at 18:46
  • Is it okay to have react version 18.2.0 & react-router-dom version 5.2.0? – Arafin Mridul Aug 03 '22 at 18:53
  • Ok, thanks for confirming that. You should update to ***at least*** `react-router-dom@5.3.3` to fix a compatibility bug between RRDv5 and Reactv18. There are other solutions available, though, in the dupe target I've linked. – Drew Reese Aug 03 '22 at 18:55

0 Answers0