Home > Software engineering >  react router dom not working whene change path
react router dom not working whene change path

Time:05-18

I am trying to render component Home and About using react-router but I get nothing, I think the problem in the index file with the store, how I can fix it, the code here link

import React from "react";
import reactDom from "react-dom/client";
import App from "./App";
import Store from "./Store";

const root = reactDom.createRoot(document.getElementById("root"));

root.render(
  <Store>
    <App />
  </Store>
);

import React, {createContext, useState} from 'react'
import Layout from './Layout'

export const Data = createContext()


function Store() {
  const [state, setState] = useState(true)
  const  value = {state, setState}

  return (
    <Data.Provider value={value}>
      <Layout/>
    </Data.Provider>
  )
}

export default Store

import React, { useContext } from "react";
import { Data } from "./Store";
import {
  BrowserRouter as Router,
  Route,
  NavLink,
  Routes,
  Link,
} from "react-router-dom";

function Layout({ children }) {
  const { state } = useContext(Data);
  return (
    <div className="layout">
      <Router>
        <div>
        <Link to="/">Home</Link>
          <Link to="/about">About</Link>        </div>
        <div className={`${state ? "hide" : "show"} mobil `}>
          <div className="children">{children} </div>
        </div>
      </Router>
    </div>
  );
}

export default Layout;

import React from "react";
import Layout from "./Layout";
import Home from "./Home";
import About from "./About";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

function App() {
  return (
    <Layout>
        <Routes>
          <Route exact path="/" element={<Home />} />
          <Route path="/About" element={<About />} />
        </Routes>
    </Layout>
  );
}

export default App;

CodePudding user response:

I just happen to see your Layout.js file.

function Layout({ children }) {
  return (
    <div>
      <!-- Router -->
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
        <div>{children}</div>
      <!-- /Router -->
    </div>
  );
}

You can't use <Router> here! Why are you using this? Just removing this nested router will make it work. Removing the tag makes it work.

CodePudding user response:

The store component should receive the children props and pass it down to the Layout, ex:

function Store({children}) {
  const [state, setState] = useState(true)
  const  value = {state, setState}

  return (
    <Data.Provider value={value}>
      <Layout>{children}</Layout>
    </Data.Provider>
  )
}
  • Related