Search code examples
reactjsreact-nativereact-native-router-flux

can't get passed param from Link to component


I have this Link in Main component:

<Link
    to={'/protected/'+this.state.username }
    //params={{ username: this.state.user }}
    style={styles.navItem_login}
    underlayColor="#f0f4f7">
    <Text style={styles.navItem_login_text}>Protected Page</Text>
</Link>

Then in App.js is the route:

<PrivateRoute path="/protected" component={Protected} />


const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

const Protected = () => <Text style={styles.header}>{this.props.username}</Text>

But this.props.username returns undefined, as well ass props.match.params.value or props.location...

How can i get the passed param in the component?. Thanks


Solution

  • Since your link is supposed to navigate to /protected/:username, you need you Protected component to be also rendered at the same route

    Link

    <Link
        to={'/protected/'+this.state.username }
        //params={{ username: this.state.user }}
        style={styles.navItem_login}
        underlayColor="#f0f4f7">
        <Text style={styles.navItem_login_text}>Protected Page</Text>
    </Link>
    

    App.js

    <PrivateRoute path="/protected/:username" component={Protected} />
    
    
    const PrivateRoute = ({ component: Component, ...rest }) => (
      <Route {...rest} render={props => (
        fakeAuth.isAuthenticated ? (
          <Component {...props}/>
        ) : (
          <Redirect to={{
            pathname: '/login',
            state: { from: props.location }
          }}/>
        )
      )}/>
    )
    

    Also since Protect is a functional component, you need to access props like

    const Protected = (props) => <Text style={styles.header}>{props.match.params.username}</Text>