Fuzzyma Fuzzyma - 11 months ago 113
React JSX Question

Get state of a child component

I am using react-draggabe. I like the idea of adding functionality to a child component by wrapping it into another like

This component manages its own state which is cool. This way I dont have to care about anything.

However: I need to get the current position of the dragged element when an event occurs (e.g. user clicks a button somewhere in another child component).
I know I could use the onStop-handler and save the new position in the state of the parent elemet. But thats a problem: I duplicate the state of the draggable component because I also save it in the parent. I dont want to do that.

What is the react-way of doing this?

I am new to rect and this thinking so I would be thankful for a good explanation.

Answer Source

You can do it with refs:

var Foo = React.createClass({       
  componentDidMount() {
    console.log(this.refs.bar.baz) // "qux"  
  render() {
    return (
        <Bar ref="bar"  />

var Bar = React.createClass({
  getInitialState: function() {
    return {baz: 'qux'};

I've made a fiddle for you with an example of accessing state form a child component. There one component increments a value, and it's sibling components renders it, accessing this value via props/refs from their parent component.