Create An Outside Click Handler in React JS
This post is about how to create an outside click handler in React using createRef()
. There are hooks that you can install to achieve this, but I wanted to try figure out myself. The feature that I created is:

As you can see above, when the search input is clicked, the placeholder, search icon is moved to the left and the cancel icon appears. When the outside of the input is clicked, they go back to the initial position and the cancel icon disappears. Let’s look at the codes below:
class Header extends Component {
constructor() {
super();
this.state = {
searchInput: “”,
searchIcon: false,
searchPlaceholder: false,
cancelIcon: false
};this.searchRef = React.createRef();}
- I have
searchIcon
,searchPlaceholder
, andcancelIcon
’s states set as above, and then createdsearchRef
usingReact.createRef()
. According to the React official documentation, Refs provide a way to access DOM nodes or React elements created in the render method. Refs can be used when we mange focus, text selection, or media playback. They are not to be overused for anything that can be done declaratively.Refs
are usually assigned in the constructor so that they can be referenced throughout the component.
<input
ref={this.searchRef}
/>
2. Then, the ref is added to the DOM element, input
in this case, using ref
attribute.
clickOutside = (e) => {
if (!this.searchRef.current.contains(e.target)) {
const { searchIcon, searchPlaceholder, cancelIcon } = this.state;
this.setState({
searchIcon: !searchIcon,
searchPlaceholder: !searchPlaceholder,
cancelIcon: !cancelIcon,
});
}
};
3. Now we have the ref to the search input, I created the event handler function using contains()
that checks if the searchRef
does NOT contain e.target
, the states of icons and placeholder are set the opposite. This will detect the click outside of the search input and get the icons and placeholder go back to the initial position. I also have onClick
handler separately that moves their positions when the input is clicked.
componentDidMount() {
document.addEventListener(“click”, this.clickOutside);
}componentWillUnmount() {
document.removeEventListener(“click”, this.clickOutside);
}
4. I added the event listener of clickOutside
in componentDidMount()
. It is invoked immediately after the component is mounted. Initialization that requires DOM nodes should go here. Then, I also added componentWillUnmount()
to remove the event listener, which is the function to be called right before the component removed from the DOM. It is usually used for a clean-up for any DOM element or timer created in componentDidMount()
.