Ad

React: Creating A Dynamic Route Based On A Prop

- 1 answer

I'm retrieving some data from a server, which i map into subcomponents in my react project.

componentDidMount() {
    axios.get('http://localhost:5000/machinelearning')
    .then(res => this.setState({projects: res.data, isLoading: false}))  
}


...
const projects = this.state.isLoading ? <CircularProgress color="secondary" size={200}/> : this.state.projects.projects[0].map((project, i) =>{
    const projectObj = Object.assign({}, project)
    console.log(projectObj)
    return(
    <div style={{padding: '15px'}} key={i+1}>
        <MachineLearningProject project={projectObj} />
    </div>

within each component, i want to make a dynamic route, that links to the a component of the same name, passed in from the server.

I make a dynamic Link on a picture on my component.

<Link to={`${props.project.name}`} >
  <CardMedia
    className={classes.media}
    image={`data:image/jpeg;base64,${props.project.picture}`}
    title="Picture"
  />
  </Link>

with a dynamic Route in the bottom of the component

 <Route path="/:project" 
component={ChatBot} //this component is hardcoded for testing purposes 
/>

ideally i want it to look like this

but it does not like anywhere, what am i doing wrong?

Ad

Answer

You need to update dynamic Route of component to

<LinkContainer to={props.project.name}>
      <Button> Label Stuff </Button>
</LinkContainer>

Ideally, your App.js should discuss which component to load based on link as Router logic resides there.

<Router>
    <Switch>
        <Route path={"Your Path"} component={"You Component"} />
    </Switch>
<Router>
Ad
source: stackoverflow.com
Ad