Home > Software design >  Reactjs: render props of Router not working
Reactjs: render props of Router not working

Time:11-15

My project not get any error, it just not render anything. Am I missing something?

In App.js, I use render props for data transmission.

import "./App.css";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Auth from "./views/Auth";
function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route
            path="/login"
            render={props => <Auth {...props} authRoute="login" />}
          />
          <Route
            path="/register"
            render={props => <Auth {...props} authRoute="register" />}
          />
        </Routes>
      </Router>
    </div>
  );
}
export default App;

and I get it on Auth.js, then check value of props.

import React from "react";
import LoginForm from "../components/auth/LoginForm";
import RegisterForm from "../components/auth/RegisterForm";
const Auth = ({ authRoute }) => {
  return (
    <>
      Learnit
      {authRoute === "login" && <LoginForm />}
      {authRoute === "register" && <RegisterForm />}
    </>
  );
};

export default Auth;

Finally, I render a Component depend on value of props

import React from 'react'

const LoginForm = () => {
    return (
        <div>
            <h1>Login</h1>
        </div>
    )
}

export default LoginForm

CodePudding user response:

I see that you are using react-router-dom v6.x. In RRDv6 the Route props no longer take render or component props, and instead take one element prop that takes a JSX literal of the component you want to render on that path.

<Router>
  <Routes>
    <Route
      path="/login"
      element={<Auth authRoute="login" />}
    />
    <Route
      path="/register"
      element={<Auth authRoute="register" />}
    />
  </Routes>
</Router>

Routes and Route

RouteProps interface

interface RouteProps {
  caseSensitive?: boolean;
  children?: React.ReactNode;
  element?: React.ReactElement | null;
  index?: boolean;
  path?: string;
}

The the routed components need to access what was previously provided via route props then they need to use the React hooks.

  • Related