Reputation: 11599
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.
Upvotes: 2
Views: 288
Reputation: 13896
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']}/>,
Upvotes: 2