当前位置:H5W3 > 问答 > 正文

React react-router-dom pass props to component

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 (
<AppBarTop isAuthenticated={isAuthenticated} />
<div className="content">
<Route path="/login" isAuthenticated={isAuthenticated} component={Login} />

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

class Login extends Component {
constructor(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:

    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:


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.


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

本文地址:H5W3 » React react-router-dom pass props to component

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址