I am new to react, I have a component UpdateInvoice
which has as props idInvoice
and a boolean isNew
. this component do two things if isNew
is true the component will add a new invoice otherwise, it will update an existing invoice identied by its idInvoice
.
I have also ListInvoices
component. I want when I click on a button "NEW INVOICE" in this component I will be able to call my UpdateInvoice
so I used React Router .
The problem
the props I send from ListInvoices
to UpdateInvoice
are empty!
in index.tsx
root.render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
<Route path="UpdateInvoice" element={<UpdateInvoice {...{idInvoice:'', isNew: null}} />} />
</Routes>
</BrowserRouter>,
);
in ListInvoices.tsx
<Button
variant="contained"
className="add"
onClick={() => navigate("/UpdateInvoice", {state: {idInvoice: '', isNew: true }})}
startIcon={<AddIcon />}>
NEW INVOICE
</Button>
I can't send the right props from index.tsx because ListInvoices
who has idInvoice
and isNew
informations
UPDATE:
ListInvoices.tsx
const [data, setData] = React.useState([] as any[]);
//when the user is authenticated using an api, I update headers value
const [headers, setHeaders] = React.useState(
{
'Authorization': ``,
'My-Custom-Header': ''
});
useEffect(() => {
if(headers.Authorization != ''){
getData(); // I fetch data from an api
}
}, [headers])
const columns: GridColDef[] = [
{ field: 'idInvoice', headerName: 'ID', minWidth: 160 },
//more columns..
]
return (
<div>
<Button
variant="contained"
className="add"
onClick={() => navigate("/UpdateInvoice", {state: {idInvoice: '', isNew: true }})}
startIcon={<AddIcon />}>
NEW INVOICE
</Button>
<Paper sx={{width: '100%', p:1}} component="ul">
<div style={{ height: 400, width: '100%'}}>
{data.length != 0 ?
<DataGrid
rows={data}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
/> : <CircularProgress className='progress'/>}
</div>
</Paper>
</div>
);
All I had to do is using useLocation
hook
in UpdateInvoice
const location = useLocation();
const [invoiceState, setInvoiceState] = React.useState<InvoiceProps>(location.state as InvoiceProps);
React.useEffect(() => {
setInvoiceState(location.state as InvoiceProps);
}, [location])
location
variable contains the state I set here
<Button
variant="contained"
className="add"
onClick={() => navigate("/UpdateInvoice", {state: {idInvoice: '', isNew: true }})}
startIcon={<AddIcon />}>
NEW INVOICE
</Button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.