Search code examples
javascriptreactjsmaterial-uireact-router-dommaterial-table

Pass prop through react router to component


I have a component, which is a material table. On click of the edit button, I have this function:

//MaterialTable.js

...
const handleEdit = (e,Data) => {
    console.log(Data)
    return(<EditFunction  id={Data.id} />)
...

This is supposed to run the EditFunction component which takes in props.id and pulls data from an API by it's 'id' and fill that into a custom form for editing and then saving again. I have the console.log in there to show that the handleEdit is actually called, which it is. All data with matching 'id' is printed in console.

Instead of calling the function directly, I want to call it via a react router. //Routers.js

...
<Router>
    <Switch>
        <Route path = '/Data/Edit' render= {props=> <Edit/>}/>
    </Switch>
</Router>
...

My goal is for the url to read something like localhost:3000/Data/Edit/id, where id is the ID number of that specific piece of data.

I don't know how to render the Link to in the MaterialTable.js file. I know this syntax is wrong below here but it's the only way I can think of doing it. //MaterialTable.js

const handleEdit = (e,Data) => {
    console.log(Data)

    return(id = {Data.id} component={Link} to=Data/Edit/id)
...

Solution

  • I figured out a solution. Below are the listed changes to the files

    //Routers.js

    ...
    <Route path = '/Data/Edit/:id' component={Edit}/>
    ...
    

    //MaterialTable.js

    const handleEdit = (e,Data) => {
        const id = Data.id
        let idUrl = '/Data/Edit/' + id
        props.history.push(idUrl)
      }
    

    The : in /Data/Edit/:id calls Edit function and finds the prop 'id' and places it's value in the router. In MaterialTable.js, that id is defined and history.push changes the route to the appropriate url.