0

I am trying to update my inner components without using refs.
Lets assume I have 3 components that A contains B, B contains C and D.
When I fire a method in A component, I want to change states of C and D.

Is there any way to do it without using refs? Something like binding childs events to parents.

Abdullah Tellioglu
  • 1,434
  • 1
  • 10
  • 26
  • Why you don't want to use refs? You are talking about binding childs event on parent (which is OK using props) but some live above you said you want update children when you call a method on parent. What exactly are you trying to archive? – keul Dec 19 '18 at 08:54
  • What about adding a props to C and D and updating it from A? – Peter Ambruzs Dec 19 '18 at 08:54
  • @PeterAmbruzs I can send an attribute to C and D and update attribute from A then I could check in componentWillReceiveProps in C and D. But I want to send function, and whenever it fires in A, it will change C and D components. – Abdullah Tellioglu Dec 19 '18 at 08:58
  • @LucaFabbri https://stackoverflow.com/questions/29503213/use-state-or-refs-in-react-js-form-components this answer explains why need to avoid refs – Abdullah Tellioglu Dec 19 '18 at 09:00
  • 1
    I think I lost. I does not understand your problem. Can you update your post with a more detailed example. – Peter Ambruzs Dec 19 '18 at 09:08

2 Answers2

0

yes you can do that using the render props below is an example of it.

Your Parent.js file looks like

import Mouse from './Mouse';
class App extends Component {
  render() {
    return (
      <div className="App">
        <Mouse render={({ x, y }) => (
          // The render prop gives us the state we need
          // to render whatever we want here.
          <h1>The mouse position is ({x}, {y})</h1>
        )} />
      </div>
    );
  }
}

Your Child comopnent should looks like

import React, { Component } from 'react'
import PropTypes from 'prop-types';
export default class Mouse extends Component {
    static propTypes = {
        render: PropTypes.func.isRequired
      }

      state = { x: 0, y: 0 }

      handleMouseMove = (event) => {
        this.setState({
          x: event.clientX,
          y: event.clientY
        })
      }

      render() {
          console.log(this.props.render);
        return (
          <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
            {this.props.render(this.state)}

          </div>
        )
      }
}

Demo

Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70
0

You have four component A, B, C, D and you want to pass a method from A to B then B to C and D via Props. Whenever the method is call from C or D it will fire to the A component and changes some state variable. Now you want to change some state variable of C and D component by triggering that method. So basically you want to access the child state in React.

There is some suggestion How to access child state in React

Rajesh Bhartia
  • 690
  • 4
  • 10