2

In this ReactJS documentation on refs, myInput is assigned to the input's ref.

<input ref="myInput" />

I have more than one input which I know only during the run time. I want to know how can I assign myInput1, myImput2 to multiple inputs?

UPDATE:

I want to clarify on why I know the number of inputs only at run time.

I have a high order component which has an input control inside of that. The high order components can be many. They are created from an array of data. I want the ref to be set for the input inside that high order component so I can show some tooltip. There is only one tooltip in the DOM and positioned based on the input control's position.

3
  • how can you only know about your inputs during runtime are they bring rendered outside of react? right about the example you posted it says: Assign a ref attribute to anything returned from render such as: Commented Jun 5, 2016 at 2:01
  • Please see my update in the question. Commented Jun 5, 2016 at 2:14
  • thanks, thats much clearer now, you could use an index to add a ref to the input when you map, something like ref={'myInput+i'} Commented Jun 5, 2016 at 2:17

1 Answer 1

2

Here is a way to do it: you can dynamically add refs as you map over the array.

http://jsfiddle.net/vhuumox0/21/

class Main extends React.Component{
    constructor(props){
    super(props);
  }
  componentDidMount() {
   console.log(this.refs); // works, shows 3
   console.log(this.refs.myInput2); // works
  }
  render() {
    const inputs = this.props.inputs.map((inp, i) => {
     return <input ref={`myInput${i}`}>{inp}</input>
    })
    return (
        <div>{inputs}</div>
    );
  }
}

ReactDOM.render(<Main inputs={['input1', 'input2', 'input3']}/>,
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.