How to pass value of ‘row‘ to EditRecord (child file)? Once I’m on EditRecord page, the props (record) of the parent’s file’s gone.
Parent File:
const [record, setRecord] = React.useState({});
return (
<TableBody>
{stableSort(props.data, getComparator(order, orderBy))
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((row, index) => (
<TableRow
className={(classes.tableAltenativeColor, classes.tableRow)}
key={index}
>
<TableCell style={{verticalAlign: 'top'}}>
<Button
onClick={() => {setRecord(JSON.stringify(row))}}
href={`${config.home}edit`}
>
<EditNoteOutlined
color={"primary"}
/>
</Button>
<EditRecord record={record}/>
</TableCell>
))}
</TableBody>
)
2
Answers
To pass the value of ‘row’ to the
EditRecord
component and ensure that it persists even when you navigate to theEditRecord
page, you need to manage the state at a higher level in your application. This typically involves using React Router to handle navigation and storing therow
data in a state management solution like Redux or React Context.Here’s a general outline of how you can achieve this:
row
data in a global state management solution like Redux or React Context.EditRecord
component as props.EditRecord
page, retrieve the necessary data from the global state and pass it as props to theEditRecord
component.Here’s a step-by-step example using React Context:
RecordContext
):App
component with theRecordProvider
to make the context available throughout the application:ParentComponent
), use theRecordContext
to set therow
data in the global state:EditRecord
component, retrieve the data from the global state using theRecordContext
:By using React Context, you can store the
row
data in the global state, making it accessible to all components in your application, including theEditRecord
component. This way, the data will persist even when you navigate to theEditRecord
page.One way to handle this is to pass the row data as a parameter in the URL, and then extract it in the child component (EditRecord). However, this is limited as you cannot pass complex objects like row in the URL directly.
A better way would be to use a state management library such as Redux or React’s Context API to store global state that can be accessed from any component in your app. Here’s a simplified version of how you could use Context API:
With this, both ParentComponent and EditRecord have access to the same record state and the setRecord function. You can use record inside EditRecord and it will always reflect the latest value set in the parent.