Source:  Twitter logo

I need to pass props to component using router. Here's my code:

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import AppBarTop from './appbar/AppBarTop';

import Login from '../pages/login/Login';
import {BrowserRouter as Router, Route} from 'react-router-dom';


class App extends Component {

    render() {

        const { isAuthenticated } = this.props;

        return (
            <Router>
                <div>
                    <AppBarTop isAuthenticated={isAuthenticated} />
                    <div className="content">
                        <Route path="/login" isAuthenticated={isAuthenticated} component={Login} />
                    </div>
                </div>
            </Router>
        );
    }
}

As you can see, isAuthenticated the prop i want to pass to Login component.

class Login extends Component {

    constructor(props) {
        super(props);
        console.log(props);
    }

    render() {
        return (
            <LoginForm />
        );
    }

}

export default connect(null) (Login);

When i log the props the isAuthenticated prop is not there. What i'm doing wrong? How can i pass the prop correctly? I followed the docs and also other discussions. From my understanding it should work. The version of react-router and react-router-dom is 4.0.0

Pass it like this:

<Route 
    path="/login" 
    render={(props) => <Login {...props} isAuthenticated={isAuthenticated}/>} 
/>

It should be available by this.props.isAuthenticated in Login Component.

Reason of {...props}:

If we don't write this then only isAuthenticated will get passed to Login component, all other values that router passes to component, will not be available inside Login component. When we write {...props} then we are passing all the values with one extra value.

And instead of using component with router use render method.

As per DOC:

Component:

When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component attribute, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render.

Render:

This allows for convenient inline rendering and wrapping without the undesired remounting.

78 users liked answer #0dislike answer #078
Mayank Shukla profile pic
Mayank Shukla

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).