I've a function that maps an object and return a list of items dynamically. Now i wish to access the inputRef for each of this element's list to apply some effect, but it is only being applied on the last and current element, and not on the rendered items
This is the rendering function:
renderSortByOptions() => {
return Object.keys(this.sortByOptions).map((sortByOption) => {
let sortByOptionValue = this.sortByOptions[sortByOption];
return (
<li
className={this.getSortByClass(sortByOptionValue)}
key={sortByOptionValue}
ref={this.inputRef} // <====
onClick={this.handleSortByChange.bind(this, sortByOptionValue)}
>
{sortByOption}
</li>
);
});
};
The ref is happening on the componentDidUpdate like this:
componentDidUpdate();
{
if (this.state.showMenu === true) {
let words = ["viejos", "nuevos", "menor", "mayor"];
words.forEach((item, i) => {
this.styleWord(this.inputRef.current, item);
});
}
}
And this is just the styleWord function:
styleWord(target, word) {
let html = target.innerHTML;
html = html.replace(new RegExp(word, "g"), "<i>" + word + "</i>");
target.innerHTML = html;
};
You need to InputRefArrary for holding reference of multiple inputs that you created dynamically. Here is an example. Please check it.
import React from "react";
export default class MultipleTextField extends React.Component {
constructor(props) {
super(props);
this.inputArr = ["name", "age", "gender"];
this.inputRefArr = [this.inputArr.length];
this.inputArr.map((input, index) => {
this.inputRefArr[index] = React.createRef();
});
this.state = {values: [this.inputArr.length]};
this.inputRef = React.createRef();
}
onChange = (event, index) => {
// 1. Make a shallow copy of the values
let values = [...this.state.values];
values[index] = event.target.value;
this.setState({values}, () => {
console.log(values, 'values')
});
};
clickHandler = (event) => {
this.inputArr.map((input, index) => {
alert(`${input} is ${this.state.values[index]}`)
})
};
render() {
return (
<form>
{
this.inputArr.map((input, index) => {
return (
<div key={index}>
<label key={index}>
{input}
<input key={index} ref={this.inputRefArr[index]} id="message" type="text"
value={this.state.values[index]}
onChange={(event) => this.onChange(event, index)}/>
</label>
</div>
);
})
}
<input type="button" value="Click Me" onClick={this.clickHandler}/>
</form>
);
}
}