Home > Mobile >  About the react router link problem state field name problem
About the react router link problem state field name problem

Time:11-22

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.

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

How can I make it work?

CodePudding user response:

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];
  • Related