Example of ReactJS Ref and React.createRef()
import React, { Component } from 'react'
export class Contact extends Component {
constructor(props){
super(props);
this.state={name:"Jahid",message:""};
this.txtNameRef=React.createRef();
}
componentDidMount(){
this.txtNameRef.current.focus();
}
messageHandler=()=>{
this.setState({message:"Thank you"});
}
nameHandler=(event)=>{
this.setState({name:event.target.value});//this.txtNameRef.current.value
}
render() {
return (
<div>
Hello {this.state.name} {this.state.message}
<input type="text" onChange={this.nameHandler} ref={this.txtNameRef} />
<button onClick={this.messageHandler}>Message</button>
</div>
)
}
}
export default Contact
Comments 0