Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

About the react router link problem state field name problem

Here is my code:

<Link 
  state={{"contact":contact}}
  to="/admin/contact/Edit"
  >
  <Button variant="warning"><Pencil/></Button>
</Link>

In the destination, I can get the contact object by the following coding:

let data = useLocation();
console.log(data.state.contact);

I want the field name to be dynamic.
So, I have tried the following coding, unfortunately in the destination, I cannot get the contact object.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let fieldName="contact"; 
 return(
  <Link 
      state={{ fieldName:contact}}
      to="/admin/contact/Edit"
    >
    <Button variant="warning"><Pencil/></Button>
  </Link>
 );

How can I make it work?

>Solution :

If you mean the property key is dynamic then the code would look something more like the following:

<Link 
  state={{ [fieldName]: contact }}
  to="/admin/contact/Edit"
>
  <Button variant="warning"><Pencil/></Button>
</Link>

fieldName is a dynamic key and would be used in the same way in the receiving component.

const { state } = useLocation();

const value = state[fieldName];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading