Grzes Slania Grzes Slania - 1 year ago 119
React JSX Question

Target dom element of react component without ref

I installed a react-component called react-geosuggest in my project. I need to find the

dom element in the
component and insert an
handler to
. Is there a way to target the
tag without altering the
component's code.

Here's the JSX

render() {
return (
id = "searchbar"
label = " "
placeholder = ""
initialValue = {this.state.location}
onChange = {this.onInputChange}
onSuggestSelect = {this.onSelection}
onClick = {this.toggleSearch}
className = {this.state.expand}
inputClassName = {this.state.expand}
// Name a calling reference
ref = 'geosuggest_component'


Here's the HTML output

<div class="geosuggest">
<div class="geosuggest__input-wrapper">
<label for="searchbar"></label>
<input class="geosuggest__input" type="text" id="searchbar">

Answer Source

You have to use vanillajs. In your component, you can access geosuggest_component ref in componentDidMount:

componentDidMount() {
    // findDOMNode returns an HTMLElement
    const node = ReactDOM.findDOMNode(this.refs.geosuggest_component);
    // Then search the label
    const label = node.querySelector('label');
    // Now, you can do anything you want with label
    label.addEventListener('click', () => console.log('clicked'))   

I use ReactDOM.findDOMNode because in this case, this.refs.geosuggest_component returns a React component. The method findDOMNode will give you the HTMLElement you need.

However, a better way to declare a ref is by using a callback:

ref={node => this.geosuggest_component = node}

Now in componentDidMount:

const node = ReactDOM.findDOMNode(this.geosuggest_component);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download