1

If I have a component like:

class Sliders extends React.Component {
  render() {
    return (
      <div>
        <Slider ref="first" update={this.props.update} />
        <Slider ref="second" update={this.props.update} />
        <Slider ref="third" update={this.props.update} />
      </div>
    )
  }
}

and I want to set up another component that accesses the value using it's ref, is there a way to do this?

class App extends React.Component {
    sliderUpdate(){
         console.log(ReactDOM.findDOMNode(this.refs.third).value)
    }
    render() {
        return (
            <div>
                <Sliders update={this.sliderUpdate} />
            </div>
        )
    }
}

this doesn't work because it seems like the refs don't carry over to the App class.

Rob
  • 3,333
  • 5
  • 28
  • 71
  • declare a function that returns the value of refs.. then pass a prop to access the function that returns it – Semi-Friends Aug 25 '16 at 10:07
  • do you have an example I could look at? This is tough for me to grasp – Rob Aug 25 '16 at 10:13
  • so you're saying my updateFunction would take the current ref as an argument? – Rob Aug 25 '16 at 11:15
  • sorry for i don't have an example available.. the idea is just like you're passing a props (which is a function) to the child component. and that child component will call the props for a certain event. which will eventually received by the parent component – Semi-Friends Aug 25 '16 at 11:53
  • 1
    check this fiddle i do for you [fidle](https://jsfiddle.net/marloeleven/w1am0s9z/1/) – Semi-Friends Aug 25 '16 at 12:03

1 Answers1

1

This can be solved without using refs.

Sample code would be as below,

const handleChange = (val) => (
    console.log(val)
)
const Application = () => (
    <div>
    <Slider handleChange={handleChange} />
    </div>
);

const Slider = (props) => (
  <div>
    <input type="text" placeholder="typesomething" onChange={(e) => props.handleChange(e.target.value)}></input>
  </div>
)

Check this codepen

anoop
  • 3,229
  • 23
  • 35