(Jump to Code | Demo) React component get element by id through reference. Before moving ahead let me inform you that React do not provide any way to access component through id. In html, we reference an element through id
and javascript uses getElementById
to access it. But, components of react are not html elements. In fact, they are not even the part of DOM. Only JSX gets converted into Html and become visible on webpages.
That’s why react has a different way of referencing components. It uses ref
. This whole process includes 3 steps –
- Creating a reference variable in constructor (for class based) or function body (for functional).
- Add the variable as component prop with name
ref
. - Use the variable anywhere in the file to access the react component as like as id in html.
Syntax for creating ref
–
For class based components –
this.componentRef = React.createRef();
For functional components –
const componentRef = React.useRef();
Syntax for referring component using ref
–
For class based –
<SomeComponent ref={node => this.componentRef.current = node} // Other Props />
For functional –
<SomeComponent ref={node => componentRef.current = node} // Other Props />
Syntax for accessing component –
// For calling function of SomeComponent this.componentRef.current.changeBackgroundToYellow();
Code Example for react component id
import React from "react"; class OtherComponent extends React.Component { state = {backgroundColor: 'white'} changeBackgroundToYellow = () => { this.setState({ backgroundColor: 'yellow' }) } render(){ return ( <div style={this.state}> <p>It's background will become yellow when you press the below button.</p> <p>This is because the component background style gets changed using ref variable.</p> <hr /> <p>Like in html - document.getElementById('id')</p> <p>In React - componentRef</p> </div> ); } } export default class App extends React.Component { constructor(props){ super(props); this.componentRef = React.createRef(); } referComponentByRef = () => { this.componentRef.current.changeBackgroundToYellow(); } render(){ return ( <div> <OtherComponent ref={node => this.componentRef.current = node} /> <hr /> <p> <button onClick={this.referComponentByRef}>Change Color</button> </p> </div> ); } }
Let’s understand this code a bit. We have defined 2 classes – OtherComponent
and App
. In OtherComponent
we have declared a function changeBackgroundToYellow()
which changes the background color to yellow.
In App
, we are creating a reference variable componentRef
using React.createRef()
. This variable is passed as ref
prop to OtherComponent
. We are also creating a button which will call a function referComponentByRef()
. This function will call the changeBackgroundToYellow()
function which was declared in OtherComponent
using reference variable componentRef
–
this.componentRef.current.changeBackgroundToYellow();
Learn more about how to call a function of child component from parent component –
Live Demo
You may also like –