Home > Software engineering >  How to send props to class component
How to send props to class component

Time:07-10

I am trying to send props to my class component. So in the parent component:

<Child contract={_contract}/>

I sent the props like this.

And in child component in one of my functions, I am calling the prop like this:

    class Mint extends React.Component {
  constructor() {
    super();
    this.state = {
      balance: [],
    };
  }

  async componentDidMount() {
    await axios.get(`https://api.cronoscan.com/api?module=stats&action=tokensupply&contractaddress=${ADDRESS}&apikey=${apikey}`)
      .then(output => {
        this.setState({
          balance: output.data.result
        })
      })
  }

  mintNft = async () => { 
    var _mintAmount = Number(document.querySelector("[name=amount]").value); 
    var mintRate = Number(await this.props.contract.methods.cost().call()); 
    var totalAmount = mintRate * _mintAmount; 
    this.props.contract.methods.mint(
      localStorage
        .getItem('walletAddress'), _mintAmount)
        .send({
           from: JSON.parse(localStorage.getItem('walletAddress')),
           value: String(totalAmount)
        });
  }

  render() {
    const { balance } = this.state;
    const { nftdata } = this.state;
    return (
                      <button onClick={mintNft}>Mint</button>
    );
  }
}

export default Mint;

but it gives an error Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'props')

Waiting for your answers. Thanks.

CodePudding user response:

Please change it

async function func() { 
  var mintRate = Number(await this.props.contract.methods.cost().call()); 
};

To

const func = async () => { 
  var mintRate = Number(await this.props.contract.methods.cost().call()); 
};

To understand this change, you need to understand the difference between Arrow Functions & General Functions. Please check https://betterprogramming.pub/difference-between-regular-functions-and-arrow-functions-f65639aba256

Codesandbox Example: https://codesandbox.io/s/laughing-snow-234or7

CodePudding user response:

If mintNft is meant to be called within the Mint component and access Mint's props, it should be declared in scope. Move the mintNft callback into the component's scope so it can access the this of the Mint component and have a defined this.props object.

class Mint extends React.Component {
  constructor() {
    super();
    this.state = {
      balance: [],
    };
  }

  async componentDidMount() {
    await axios.get(`https://api.cronoscan.com/api?module=stats&action=tokensupply&contractaddress=${ADDRESS}&apikey=${apikey}`)
      .then(output => {
        this.setState({
          balance: output.data.result
        })
      })
  }

  mintNft = async () => { 
    var _mintAmount = Number(document.querySelector("[name=amount]").value); 
    var mintRate = Number(await this.props.contract.methods.cost().call()); 
    var totalAmount = mintRate * _mintAmount; 
    this.props.contract.methods.mint(
      localStorage
        .getItem('walletAddress'), _mintAmount)
        .send({
           from: JSON.parse(localStorage.getItem('walletAddress')),
           value: String(totalAmount)
        });
  }

  ...

  render() {
    const { balance, nftdata } = this.state;
    return (
      <button onClick={this.mintNft}> // <-- pass as callback
        Mint
      </button>
    );
  }
}
  • Related