React: creating and referencing dynamic component refs

Viewed 13748

I'm trying to keep track of an arbitrary amount of sub components.

Normally you would just reference this.refs.refName, but in my case I have an arbitrary amount of refs I need to keep track of.

Here's a concise example:

var NamesList = React.createClass({
  getAllNames: function() {
    // Somehow return an array of names...

    var names = [];
    this.refs.????.forEach(function (span) {
      names.push(span.textContent);
    })
  },

  render: function() {
    var names = ['jack','fred','bob','carl'];
    var spans = [];

    names.forEach(function (name) {
      spans.push(<span contentEditable={true} ref='?????'>name</span>);
    });

    return (
      <div>
        {spans}
      </div>;
    );
  }
});

ReactDOM.render(<NamesList></NamesList>, mountNode);

If I'm approaching the problem incorrectly let me know. My desired outcome is to pass in data from a RESTful service to a React component, allow the user to edit that data, and export it again when needed. I've been unable to find an answer to this in the React refs docs.

3 Answers

This is probably the simplest way to create dynamic refs that I have found.

Also this solution works without any issues from TypeScript as well.

const Child = props => <input ref={refElem => setRef(props.someKey, refElem)} />

class Parent extends Component {

    setRef = (key, ref) => {
      this[key] = ref; // Once this function fires, I know about my child :)
    };

    render(){
        return (
          {myList.map(listItem => <Child someKey={listItem.key} setRef={this.setRef} />)}
        )
    }
}

Anyways hope this helps someone.

Related