Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js
Home  • Programming • React

Example of ReactJS Ref and React.createRef()

code-import-react-component-from
  1. import React, { Component } from 'react'
  2.  
  3. export class Contact extends Component {
  4. constructor(props){
  5. super(props);
  6. this.state={name:"Jahid",message:""};
  7. this.txtNameRef=React.createRef();
  8. }
  9.  
  10. componentDidMount(){
  11. this.txtNameRef.current.focus();
  12.  
  13. }
  14.  
  15. messageHandler=()=>{
  16. this.setState({message:"Thank you"});
  17. }
  18.  
  19. nameHandler=(event)=>{
  20. this.setState({name:event.target.value});//this.txtNameRef.current.value
  21.  
  22. }
  23. render() {
  24. return (
  25. <div>
  26. Hello {this.state.name} {this.state.message}
  27. <input type="text" onChange={this.nameHandler} ref={this.txtNameRef} />
  28. <button onClick={this.messageHandler}>Message</button>
  29. </div>
  30. )
  31. }
  32. }
  33.  
  34. export default Contact

Comments 0


Copyright © 2025. Powered by Intellect Software Ltd