class SearchInput extends React.Component {
constructor(props) {
super(props);
this.searchInputRef = React.createRef(); // 👈️ LOOK HERE
}
onFormSubmit = (e) => {
e.preventDefault();
// const query = e.target.querySelector("#searchInput").value; // 👈️ LOOK HERE
const query = this.searchInputRef.current.value;
console.log(query);
};
render() {
return (
<form onSubmit={this.onFormSubmit}>
<div className="input-group-text">
{this.props.label}
<input
type="text"
className="form-control"
id="searchInput"
aria-describedby="emailHelp"
placeholder="Search"
ref={this.searchInputRef}
/>
<button type="submit" className="btn btn-primary">
<i className="fas fa-search"></i>
</button>
</div>
</form>
);
}
}
I'm very new to ReactJS, but I'm having hard times with it, I have two questions about my component above:
- on the first
// 👈️ LOOK HERE
comment above, you see, I'm saving the references to the class instance itself (in the constructor) which leads to two downsides:
- The constructor will become very messy later when I add 7 or 8 references inside of it, which makes it non-clean code.
- We're saving the reference to the object body of the class instance, do you think this is a clean-code? maybe there should be something in React that allows me to store all the references inside one property may be called "refs", so the instance of that class would look like the following:
{
refs: {
searchInputRef: ...
// later
buttonRef: ...
button2Ref: ...
iconRef: ...
}
state: ...
// the rest of the component object
}
Which is more cleaner if you ask me. If I'm wrong, please let me know.
- on the second comment
// 👈️ LOOK HERE
of course you can see I don't actually need a reference in my case, so why I'm using ref sys~? I can simply get the input frome.target.querySelector("#searchInput")
as simple as it looks like, why folks are always saying it's a shame and a bad practice to use my beloved querySelector to reference DOM elements when using React?