0

Basically what I want to do is create a react portfolio project that contains and showcases all of my react projects. But I don't know how to render a project based on a url value.

What I mean is,

   <Route path='/projects/:projectName' component={Project}></Route>

I want to render a component based on the :projectName vakue. Or maybe create a Project component that just renders the given project based on the url value. Is that even possible? I know I can use match to get the :projectName value, but how could I use it to render a component?

2 Answers 2

1

There are few approaches
1. As mentioned above to let project component decide what should be rendered based on match.params

const routes = {
 'my-route1': <MyComponent1 />,
 'my-route2': <MyComponent2 />
}

const Project = props => {
  const { projectName } = props.match.params
  return routes[projectName] || <DefaultComponent />
}
  1. You may define your own routes components who will decide which component to Render based on state. It is helpful when you need to create master pages or templates and do not want any dependencies on match inside other components.
    const PrivateRoute = ({ component: Component, ...rest }) => {
      const func = props => (!!rest.isUserAllowedToNavigate()
        ? <Component {...props} />
        : (
          <Redirect to={
              {
                pathname: '/login',
                search: props.location.pathname !== '/' && queryStringComposer({
                  redirect_from: props.location.pathname || getQueryStringParam('redirect_from')
                })
              }
            }
          />
        )
      )
      return (<Route {...rest} render={func} />)
    }
    /* Connecting to redux */
    const PrivateRouteConnected = connect(mapStateToProps, mapDispatchToProps)(PrivateRoute)
    /* Using as normal routes */
    <PrivateRouteConnected exact path="/dashboard" component={Dashboard} />
Sign up to request clarification or add additional context in comments.

Comments

0

your Project component can handle the logic to render a different component based on the URL param. For example:

const Project = props => {
  const { projectName } = props.match.params
  if (projectName === project1) {
    return <ProjectOne addProps={addProps} />
  }
  if (projectName === project2) {
    return <ProjectTwo />
  }
  return <DefaultProject />
}

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.