Reputation: 602
I installed a react-component called react-geosuggest in my project. I need to find the <label>
dom element in the <Geosuggest>
component and insert an onClick
handler to <label>
. Is there a way to target the <label>
tag without altering the <Geosuggest>
component's code.
Here's the JSX
render() {
return (
<div>
<Geosuggest
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'
/>
</div>
);
}
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">
</div>
</div>
Upvotes: 5
Views: 3007
Reputation: 1006
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);
Upvotes: 2