yieniggu
yieniggu

Reputation: 404

Can't destructure props in child component

I'm getting some trouble on destructuring props when passing an object to a child component. This object has 2 values, one is another object and the second is a function.

This is my code in case any of you can help: Parent cmp:

export const AdminScreen = () => {
  const {kolorTokenContract, setContract} = useContext(ContractsContext);

  console.log("contract from admin: ", kolorTokenContract);

  return (
    <div className="container">
      <h1>Administrator Screen</h1>
      <hr />

      <div className="row align-items-center">
        <ERC20AdminForm props={{kolorTokenContract, setContract}} />
        <TokenInfo {...kolorTokenContract} />
      </div>
      <hr />
      <Balance />
    </div>
  );
};

Child cmp:

export const ERC20AdminForm = ({kolorTokenContract, setContract}) => {
  //console.log("props from erc20admin form: ", props);
  console.log("contract from erc20admin form: ", kolorTokenContract);

  return (
    <div className="col-8 col-md-6 col-sm-4 ">
      <MintingForm props={kolorTokenContract} />
      <SetVaultForm />
      <TransferOwnershipForm />
    </div>
  );
};

If i log the "kolorTokenContract" i just get undefined :(. Thanks in advance for any help!

Upvotes: 1

Views: 571

Answers (2)

fahad991
fahad991

Reputation: 482

In your admin screen you should check for the kolorTokenContract . what does the context return? from where do you get the value of kolorTokenContract, does it come from an api? if it is then I am guessing while defining the state you didn't give it a value. For solution, you can give an empty object while defining the kolorTokenContract in your context or you can set a default value

const {kolorTokenContract = {}, setContract} = useContext(ContractsContext);

Upvotes: 0

Giorgi Gvimradze
Giorgi Gvimradze

Reputation: 2129

For Child component:

const ERC20AdminForm = (props:any) => {
console.log("contract from erc20admin form: ", props.kolorTokenContract);

  return (
    <div className="col-8 col-md-6 col-sm-4 ">
      <MintingForm kolorTokenContract={props.kolorTokenContract} />
      <SetVaultForm />
      <TransferOwnershipForm />
    </div>
  );
};

Call from a parent with separate props:

<ERC20AdminForm kolorTokenContract={kolorTokenContract} setContract={setContract} />

This is a sandbox code for proof of concept.

Upvotes: 1

Related Questions