Reputation: 181
I have a question, I tried looking online and couldn't find what I needed but that's probably because I couldn't word my question properly.
I have a React project I'm putting together and I want to have user profile pages for people. Here is what I have so far.
<Route path="/profile/:user" render={(routeProps) => (<Profile {...routeProps} {...this.state} /> )}/>
This is in my index.js, to set the route for my profile pages for different users and the following is what I have for my profile page
import React from 'react';
import ReactDOM from 'react-dom';
import { NavLink } from 'react-router-dom';
export class Profile extends React.Component{
constructor(props){
super(props);
this.state={
user: this.props.user,
fullname: this.props.fullname,
picture: this.props.picture
};
}
render(){
return(
<h1>{this.state.fullname}</h1>
);
}
}
Now the question I have is this. I want the profile page to only load and render the users full name if the URL matches the userID given by 'user' in the state
in my index.js I have hardcoded user and fullname values to test this, they are set like this
constructor(props){
super(props);
this.state = {
user:"AFC12345",
fullname:"Bob Ross"
};
I want to only have the Profile page rendered when I visit "http://localhost:8080/#/Profile/AFC12345" currently it renders the profile page for any "Profile/xxxx" I go to.
Upvotes: 0
Views: 5505
Reputation: 1280
Another way would be to consider that Profile
container as a protected URL and use the same dynamic as the authentication flow.
import React from 'react';
import { Redirect } from 'react-router-dom';
const ProtectedProfile = ({ component: Component, ...rest }) => (
<Route {...rest} render={ props => (
props.user === props.match.params.user ? (
<Component {...props} /> ) : (
<Redirect to={{ pathname: '/404' }} /> )
)} />
);
Then in your App/index.js
<ProtectedProfile path="/profile/:user" component={Profile} />
Upvotes: 4
Reputation: 814
i would do something like this in the render function
let viewToRender
if (this.state.user === this.props.match.params.user) {
viewToRender = <p>{this.state.fullname}</p>
}else{
viewToRender = <p>Ids don't match</p>
}
....
return (){ viewToRender }
Upvotes: 1