Search code examples
javascriptreactjscomponentsprop

React - Get property of a component inside its own declaration to use its value in another property?


I wonder if it is possible to get property of a component inside its to use the same value in another property ? It is hard to describe so I will give an example.

In this one : <Link className="link" to="/about" onClick={(e) => {this.clickMenuLink(e, "/about")}}>About</Link>

I wonder if it is possible to turn it in something like this bellow, in order to make the second parameter of the clickMenuLink function dynamic, by getting automaticaly the value you set in the to= property : <Link className="link" to="/about" onClick={(e) => {this.clickMenuLink(e, to)}}>About</Link>

Thank you in advance.


Solution

  • It's not possible directly that way, because the to prop is only defined inside the Link component, while you're trying to use it's value in the definition of a callback.

    You could wrap the Link component with your own MyLink component.

    <MyLink to="/about" onClick={this.clickMenuLink} />
    

    And then in render of MyLink

    render() {
      return <Link to={this.props.to} onClick={e => this.props.onClick(e, this.props.to)} />;
    }