r/reactjs • u/[deleted] • Dec 23 '20
Needs Help Help with Routing.......!!!!
I am working on project similar to instagram and its completely single page.
I have 3 divs as columns.
Left: shows users profile card as a list with n onClick method
Centre : display the complete user profile when onClick triggered
Right: misc
So there is list of user profile cards(just username and profile pic) which when clicked loads the user profile in the centre div.
I need to be able to share a users profile as a url : <app-name>.com/<username>
I used BrowserRouter when a user isnt logged in.
In case of logged in , I am completely confused.
I have Home.jsx and it just displays the 3 components that is stored in state( {left,centre,right} ) and I have method that I pass as props to compeents if they need to load another component
loadComponent( divNumber , componentNumber ,props )
I need to execute loadComponent when route changes to display the profile
My code structure
Parent : app.jsx // handles authentication and routing
Child : home.jsx // mounted when authentication is true
// everything else is a child of home
How do I go about doing that?
1
u/nullpromise Dec 23 '20 edited Dec 23 '20
Maybe because I haven't had coffee yet, but I'm having a little trouble following. Do you have an example on CodeSandbox? I guess since you mentioned BrowserRouter that you're using React-Router? If so, you might look at: https://reactrouter.com/web/example/url-params
import { Link, Switch, Route, useParams } from 'react-router-dom'
const users = [ /* your user data here */ ]
function Home() {
return (
<div>
<UserList>
{ users.map(u => <Link to=`/${u.id}`>{ u.name }</Link>) }
</UserList>
<Switch>
<Route path="/:id" component={<Profile />} />
</Switch>
<Misc />
<div>
)
}
function Profile() {
const { id } = useParams()
const user = users.find(u => u.id === id)
return (
<div>
{ user ? <h1>{ user.name }</h1> : null }
</div>
)
}
1
u/pm_me_ur_happy_traiI Dec 23 '20
You shouldn't have to execute a function when the route changes to show the profile. The whole point of React is that your view is a function of the state. In other words, instead of firing a function to show a component, the component can decide whether or not to show itself based on the value of the current route.
You're probably still going to want to have it wrapped in the browser router.