Use a Username in a Path to Route a Component (React-router-dom)

Viewed 271

I am having a hard time setting up my react-router so that when the path matches the user's username, the userProfile component will be routed and show individually. For example, when the URL is http://localhost:3000/myusername, the userProfile component will only show. I'm kind of confused on how it will work if someone just pastes the entire link instead of being directed to someone's page through the UI.

<Switch>
    <Route path="/" component={userProfile} /> 
    <PrivateRoute exact path="/test2" component={test2} />
    <PrivateRoute exact path="/test3" component={test3} />
</Switch>

Any help would be appreciated!

2 Answers

You can use this method and access to username in test3 component and handle getting data and showing this page

<Switch>
    <Route path="/" component={userProfile} /> 
    <PrivateRoute exact path="/test2" component={test2} />
    <PrivateRoute exact path="/:username" component={test3} />
</Switch>

I found that if you just use /:id in the path, then the path extension will pass automatically down to the userProfile component when you use the const {id} = useParams() function in the userProfile component. Then I passed the _id down as a prop from the userProfile component to the Info component so that it can be used to automatically fetch data in a useEffect() and redux dispatch() function. Oh and also, the <Route path="/:id" component={userProfile} /> needs to be an exact path and must go to the bottom of the Route Switch list so that it doesn't get picked first.

<Switch>
    <PrivateRoute exact path="/test2" component={test2} />
    <PrivateRoute exact path="/test3" component={test3} />
    <Route exact path="/:id" component={userProfile} /> 
</Switch>

const Profile = () => {
  const { id } = useParams();

  return (
    <div>
       <Info _id={id} />
    </div>
  );
};

export default Profile;

const Info = (props) => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getProfileInfo(props._id));
  }, []);

  return (
    <div></div>
  );
};

export default Info;

Related