Refs and the DOM in React JS.
In this chapter, you will learn about Refs and the DOM in React JS. Refs method provides a way to access DOM nodes or React elements created in the render method. In the typical React data-flow approach, props are the only way that parent components interact with their children. To modify a child, you re-render it with new props. However, there are a few cases where you need to imperatively modify a child outside of the typical dataflow. The child to be modified could be an instance of a React component.
When to Use Refs?
There are a few good use cases for refs:
- Managing focus, text selection, or media playback.
- Triggering imperative animations.
- Integrating with third-party DOM libraries.
Let’s create an example of focusing on an input field.
Step 1:
Create the file src/components/manager/Manager.js if you have it already paste the below code snippet
import React from "react"; import './Manager.css' import PropTypes from 'prop-types' const manager = props => { return ( <div> {props.isManagerLoggedin ? ( <div> <h2>Welcome to your dashboard</h2> {props.employee.map(item => ( <li key={item.name}> Name: {item.name}, ID: {item.empId}</li> ))} <button onClick={props.logout}>Logout</button> </div> ) : ( <div> <button onClick={props.login}>Login</button> </div> )} </div> ); }; manager.propTypes = { isManagerLoggedin: PropTypes.bool, login:PropTypes.func, logout:PropTypes.func, employee:PropTypes.array }; export default manager;
Step 2:
Create the file src/components/hoc/Container.js if you have it already paste the below code snippet
import React from 'react'; const container = (props) => ( <div className={props.divClassName}> {props.children} </div> ); export default container;
Step 3:
Create the file src/App.js if you have it already paste the below code snippet
import React, { Component } from 'react'; import './App.css'; import Manager from './components/manager/Manager'; import Container from './components/hoc/Container'; class App extends Component { constructor(props) { super(props); this.login = this.login.bind(this); this.logout = this.logout.bind(this); this.state = { isManagerLoggedin: false, employee: [ {name:'Stark', empId:'123'}, {name:'John', empId:'124'}, {name:'Mickel', empId:'125'}, {name:'Clark', empId:'126'} ] }; } componentDidMount() {} login = e => { this.setState({ isManagerLoggedin: true }); }; logout = e => { this.setState({ isManagerLoggedin: false }); }; render() { return ( <Container divClassName='App'> <h1>Welcome to react JS tutorial</h1> <Manager isManagerLoggedin={this.state.isManagerLoggedin} login={this.login} logout={this.logout} employee={this.state.employee} /> </Container> ); } } export default App;
Hit the URL: http://localhost:3000/, as we can see in the below output, it automatically focuses an input field.
One thought on “Refs and the DOM in React JS”
Comments are closed.