KeepMyselfHumble
KeepMyselfHumble

Reputation: 23

React: Passing Props not working. Am I missing something?

as you may get from the title, passing props in react is not working. And i don´t get why.

import styled from 'styled-components';


const Login = (props) => {
    return<div>Login</div>

}

export default Login;

On my App.js page here is the following:

import './App.css';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Login from './components/Login.js';

function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route exact path="/" >
            <Login />
          </Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;

Problem: if i start the script and render the page, nothing is shown. What am I doing wrong?

Upvotes: 1

Views: 985

Answers (2)

Drew Reese
Drew Reese

Reputation: 203542

<Login />... the Login component isn't passed any props so I wouldn't expect to see any in the component. Your issue is a misunderstanding how the Route component works. The only valid children of the Route component is another Route component in the case of nesting routes, otherwise, the routed content is passed on the Route component's element prop as a ReactNode, a.k.a. JSX.

Route

declare function Route(
  props: RouteProps
): React.ReactElement | null;

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

The Login component should be passed to the element prop.

function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/" element={<Login />} />
        </Routes>
      </Router>
    </div>
  );
}

For more details/explanation see Why does <Route> have an element prop instead of render or component?

Upvotes: 0

Hossein hossein
Hossein hossein

Reputation: 147

You should pass <Login /> as the element. Try this code:
App.js:

import './App.css';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Login from './components/Login.js';

function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route exact path="/" element={<Login />} />
        </Routes>
      </Router>
    </div>
  );
}

export default App;

Upvotes: 3

Related Questions