import React, { Component, useRef } from "react"; import PropTypes from "prop-types"; export default class App extends Component { constructor(props) { super(props); this.myref = React.createRef(); this.myrefSecondInstance = React.createRef(); this.childref = React.createRef(); this.state = { defaultOrNew: "default", firstNameDefault: "Arhan", lastNameDefault: "Kamra", firstName: this.myref.value, }; } static propTypes = { prop: PropTypes, }; componentDidMount() { this.myref.current.focus(); this.childref.current.me(); } handleClick = () => { this.myref.current.focus(); }; handleClickSecondInstance = () => { this.myrefSecondInstance.current.focus(); }; handleClickBlur = () => { this.myref.current.blur(); }; handleClickBlurSecondInstance = () => { this.myrefSecondInstance.current.blur(); }; changeName = () => { this.setState(() => { return { defaultOrNew: "new", firstNameDefault: this.myref.current.value, lastNameDefault: this.myrefSecondInstance.current.value, firstName: this.myref.current.value, lastName: this.myrefSecondInstance.current.value, }; }); }; render() { return ( <div className="app"> <input type="text" onChange={this.changeName} defaultValue={this.state.firstNameDefault} ref={this.myref} /> <input type="text" onChange={this.changeName} defaultValue={this.state.lastNameDefault} ref={this.myrefSecondInstance} /> <button onClick={this.handleClick}>Focus input</button> <button onClick={this.handleClickBlur}>Remove focus</button> <button onClick={this.handleClickSecondInstance}>Focus inputSecondInstance</button> <button onClick={this.handleClickBlurSecondInstance}>RemoveSecondInstance focus</button> <p> Hi my <strong>{this.state.defaultOrNew}</strong> name is {this.state.firstNameDefault}{" "} {this.state.middleNameDefault} {this.state.lastNameDefault} </p> <Child ref={this.childref} /> </div> ); } } class Child extends Component { me = () => { console.log("sophisticated coder"); window.alert("xyz abc"); }; render() { return <div>{4 + 4}</div>; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter