React Tips — Spies, Global Events, and Nav Links

Photo by Gary Sandoz on Unsplash

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Register Event with useEffect Hooks

We can register events within the useEffect callback.

For instance, we can write:

const App = () => {
const [userText, setUserText] = useState('');
const handleUserKeyPress = useCallback(event => {
const { key, keyCode } = event;
if (keyCode === 32) {
setUserText(prevUserText => `${prevUserText}${key}`);
}, []);
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
}, [handleUserKeyPress]);
return (

We listen to the keypress event on the window.

If we press the space key, then the key code will be registered.

Then we can use that to append the state string with the key text.

We just keep appending the key code to the state string.

Automatic Redirect After Login with React Router

We can automatically redirect after login with React Router.

To do that, we get the history object and call push on it.

For instance, we can write:

fetch('/login', {
.then(response => response.json())
.then(data => {

We call this.props.history.push to do the redirect.

The prop is available once we pass the component into the withRouter higher-order component.

Set Types on useState React Hook with TypeScript

To set the state of the useState hook, we can pass in a type parameter with the useState function.

For instance, we can write:

const [user, setUser] = useState<IUser>({ name: 'james' });

IUser is an interface that has the name string property.

For a full example, we can write:

import React, { useState, Dispatch } from 'react';interface IUser {
name: string;
const App = () => {
const [user, setUser] = useState<IUser>({ name: 'james' });
const clickHander = (stateSetter: Dispatch<IUser>) => {
stateSetter({name : 'james'});
return (
<button onClick={() => { clickHander(setUser) }}>Change Name</button>

setUser has the type Dispatch<IUser> .

Dispatch is from the React package.

The type parameter in Dispatch should match the type we pass into useState .

Jest spyOn Call on a Component

To check if a component’s method is called, we can use the jest.spyOn method to check if it’s called.

For instance, we can write the following test:

describe('simple test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const instance = app.instance()
const spy = jest.spyOn(instance, 'onClick')
const p = app.find('.button')

We check if the onclick method is called if we get the p element and call it.

First, we mount the App component with the shallow function.

Then we get the instance with the instance method.

Next, we call jest.spyOn on the component method that we expect to call if we click the button.

We call forceUpdate to update our component that we want to test with the spy.

Then we find the p element with the class button .

Then we call simulate('click') on that to click it.

And then we check if the mock function has been called.

This works for class components since they have instance methods.

How to set the Inline Style of background-color with React

We can set the inline style of background color with the backgroundColor property.

For instance, we can write:

<a style={{ backgroundColor: 'orange' }}>orange</a>

We set the backgroundColor to 'orange' with the camel-cased key.

Set activeClassName for Wrapper Element of Link or IndexLink in React Router

We can create a wrapper element for a link by creating a component.

The activeClassName value can be passed in from the props.

For instance, we can write:

import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
class NavHeaderextends Component { render (){
return (
<NavLink activeClassName="active" exact to="/">home</NavLink>
<NavLink activeClassName="active" to="/about">About</NavLink>
<NavLink activeClassName="active" to="/courses">profile</NavLink>

We use the NavLink component to create the navigation links.

activeClassName is a string that we can set to the class that’s applied when the link is active.

to is the path that the link goes to.

Photo by Charlie Green on Unsplash


We can make links with special styles when it’s active with React Router’s NavLink component.

useEffect hooks can be used to listen to global events.

We can mock class instance methods with Jest spies.

React useState hooks can state change functions can have types added to them.

Web developer. Subscribe to my email list now at Email me at

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store