0

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.

2 Answers 2

4

Another way would be to consider that Profilecontainer 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} />
Sign up to request clarification or add additional context in comments.

Comments

1

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 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.