Logo


How to use ref in react js


the following example shows how to use refs to clear the input field .clearinput function searches for element with ref="myInput" value,rests the state and add focus on itafter the button is clicked

once the button is clicked and it will be focused and cleared out


App.js file is displayed below:

1import "./styles.css";
2import React from "react"
3import ReactDOM from "react-dom"
4
5export default class App extends React.Component {
6  constructor(props)
7  {
8    super(props)
9    this.state={
10      value:""
11
12    }
13     this. handleChange=this. handleChange.bind(this);
14    this.clearinput=this.clearinput.bind(this);
15
16  };
17  handleChange=(e)=>
18  {
19    this.setState({
20      value:e.target.value
21    });
22
23  }
24
25  clearinput=()=>
26  {
27    this.setState({value:""});
28    ReactDOM.findDOMNode(this.refs.myinput).focus()
29
30  }
31  render() {
32    return <>
33    
34    <input value={this.state.value} onChange={(e)=>this.handleChange(e)} ref="myinput"/>
35<button onClick={(e)=>this.clearinput(e)}>clear</button>
36    </>;
37  }
38}

Here is the link of live example which we done so far:
Click here

About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share