2
\$\begingroup\$

Im trying to access the attribute directly in the parent component, that why Im using the ref method. here an example of why Im trying to achieve: https://stackblitz.com/edit/react-lupsr2 Im accessing it using some for in loop currently, so far it works, although I think there is probably more efficient way to do the job. to me, using a for in loop is probably very expensive, and there is probably other way, more ecologic to achieve the end.

Here my react snippet:

class App extends Component {

  constructor(prop) {
    super(prop);
    this.children=React.createRef()
    this.state = {
      name: 'React'
    };
  }

  componentDidMount(){ 
    for (var key in this.children.current) {
      if(key.includes("__reactEventHandlers"))
        // ACCESS OBJECT HERE
        return console.log("in componentdidmount for in:", this.children.current[key].test)
    }
  }

  render() {
     console.log("this.children in render: ", this.children)
    return (
      <div>
        <Hello name={this.state.name} />
        <button  onClick= {()=> console.log("children: ", this.children)} >   click to display children</button>
        <p>
          Start editing to see some magic happen :)
        </p>
        <div ref={this.children} test={awesomeObject} />
      </div>
    );
  }
}

any hint would be great, thanks

\$\endgroup\$
  • \$\begingroup\$ In React data is passed from Parent to Child. A child component should not have direct access to its parent. It's anti-pattern. That being said, I do not understand what you're attempting to achieve. Could you elaborate more please ? There is always a better way than via the Parent (Provider/Context, Mobx, etc..) \$\endgroup\$ – kemicofa Jun 15 at 14:56
  • \$\begingroup\$ @kemicofa hi and thanks you for your answer. Im trying to make a component having a specific style inside the parent. So I would register some variable to allow them to work with parent. Using a sub-component could be an option \$\endgroup\$ – Webwoman Jun 18 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.