Home > Enterprise >  How to re-route correctly in React.js? Always renders white page
How to re-route correctly in React.js? Always renders white page

Time:04-04

When I visit my default url http://localhost:3000/ React is rendering the Landing component which makes sense to me. I'm using react-router-v6.

// App.js

class App extends Component {
  render() {
    return (
      <Fragment>
        <Routes>
            <Route exact path="/" element={<Landing />} />
            <Route exact path="/login" element={<Login />} />
        </Routes>
      </Fragment>
    );
  }
}

export default App;

Now in the Landing component I do have more Routes which however don't render anything but a white page like e.g. Team (I removed imports from code, all is properly imported).

// Landing.js

function Landing(props) {
    return (
        <Fragment>
            <CoreWrapper>
                <div className={styles.landingWrapper}>Test</div>
              </CoreWrapper>

            <Routes>
                <Route exact path="/team" element={<Team />} />
                <Route exact path="/careers" element={<Careers />} />
                <Route exact path="/contact" element={<Contact />} />
            </Routes>
        </Fragment>
    )
}

export default Landing;
// CoreWrapper.js

const CoreWrapper = (props) => {
    return (
        <Fragment>
            <Header/>
            <div className={styles.bodyWrapper}>{props.children}</div>
            <Footer/>
        </Fragment>
    )
}

export default CoreWrapper
// Team.js

const Team = () => {
    return (
        <CoreWrapper>
            <div className="teamWrapper">Team Here</div>
        </CoreWrapper>
    )
}

export default Team;

CodePudding user response:

if you are using react-router v6 version then exact doesn't support anymore

I assume you put BrowserRouter at root component.

class App extends Component {
  render() {
    return (
      <Fragment>
        <Routes>
            <Route path="/" element={<Landing />} />
            <Route path="/login" element={<Login />} />
        </Routes>
      </Fragment>
    );
  }
}

export default App;
function Landing(props) {
    return (
        <Fragment>
            <CoreWrapper>
                <div className={styles.landingWrapper}>Test</div>
              </CoreWrapper>

            <Routes>
                <Route path="/team" element={<Team />} />
                <Route path="/careers" element={<Careers />} />
                <Route path="/contact" element={<Contact />} />
                // make whatever default routes of landing component that's your choice
                <Route path="*" element={<Navigate to="/team" />} />
            </Routes>
        </Fragment>
    )
}

export default Landing;

but that's the official documented way of doing it I suggest you also do like the documentation way

nested-routes

  • Related