I have a React component and I want to toggle a css class when clicked.
So I have this:
export class myComponent extends React.Component {
construc
The Lint rule you are referring to is called no-string-refs and warns you with:
"Using string literals in ref attributes is deprecated (react/no-string-refs)"
You are getting this warning because have implemented the deprecated way of using refs (by using strings). Depending on your React version, you can do:
constructor() {
super();
this.btnRef= React.createRef();
this.state = { clicked: false };
this.handleClick = this.handleClick.bind(this);
}
render() {
return (
);
}
constructor() {
super();
this.btnRef; //not necessary to declare the variable here, but I like to make it more visible.
this.state = { clicked: false };
this.handleClick = this.handleClick.bind(this);
}
render() {
return (
this.btnRef = el} className="glyphicon">
);
}
For even better readability, you could also do:
render() {
let myRef = (el) => this.btnRef = el;
return (
);
}
Have a look at what the official documentation says on Refs and the DOM, and this section in particular:
Legacy API: String Refs
If you worked with React before, you might be familiar with an older API where the
refattribute is a string, like"textInput", and the DOM node is accessed asthis.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently usingthis.refs.textInputto access refs, we recommend the callback pattern instead.