More Examples of Refs in React
Let’s look at some of the React code examples of refs. The examples will provide a better learning experience for master ReactJS refs.
Example 1: In this example, we use refs to add a callback function indirectly with the help of the update function and onChange event handler.
// using refs
class App extends React.Component {
constructor() {
super();
this.state = { sayings: "" };
}
update(e) {
this.setState({ sayings: this.refs.anything.value });
}
render() {
return (
<div>
Mukul Says <input type="text" ref="anything"
onChange={this.update.bind(this)} />
<br />
<em>{this.state.sayings}</em>
</div>
);
}
}
ReactDOM.render(< App />, document.getElementById('root'));
Output:
Example 2: In this example, we directly define callback function within ref.
// Filename - App.js
// callback used inside ref
class App extends React.Component {
constructor() {
super();
this.state = { sayings: "" };
}
update(e) {
this.setState({ sayings: this.a.value });
}
render() {
return (
<div>
Mukul Says{" "}
<input
type="text"
ref={(call_back) => {
this.a = call_back;
}}
onChange={this.update.bind(this)}
/>
<br />
<em>{this.state.sayings}</em>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Output:
ReactJS Refs
ReactJS Refs are used to access and modify the DOM elements in the React Application. It creates a reference to the elements and uses it to modify them.
Table of Content
- What are React refs ?
- Creating refs in React
- Accessing Refs in React
- When to use refs
- When not to use refs