Categories
React Tips

React Tips — Spies, Global Events, and Nav Links

Spread the love

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 (
    <div>
      <p>{userText}</p>
    </div>
  );
}

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', {
  username,
  password
})
  .then(response => response.json())
  .then(data => {
    this.props.history.push("/");
  })

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 (
     <div>
      <button onClick={() => { clickHander(setUser) }}>Change Name</button>
    </div>
  )
}

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')
     instance.forceUpdate();

     const p = app.find('.button')
     p.simulate('click')
     expect(spy).toHaveBeenCalled()
 })
})

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 (
      <header>
        <ul>
          <li>
             <NavLink activeClassName="active" exact to="/">home</NavLink>
          </li>
          <li>
             <NavLink activeClassName="active" to="/about">About</NavLink>
          </li>
          <li>
             <NavLink activeClassName="active" to="/courses">profile</NavLink>
          </li>
        </ul>
      </header>
    );
  }
}

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.

Conclusion

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *