Categories
React Answers

How to Add Click Event Handlers for Divs in React?

Oftentimes, we want to add click event handlers to div elements in our React components.

In this article, we’ll look at how to add click event handlers to div elements in our React components.

Add Click Event Handlers for Divs in React

We can use onClick with divs if we provide it a size.

For instance, we can write:

class App extends React.component {
  constructor() {
    this.state = {
      color: 'black'
    };
  },

  changeColor() {
    const newColor = this.state.color == 'white' ? 'black' : 'white';
    this.setState({
      color: newColor
    });
  },

  render() {
    return (
       <div>
          <div
             style = {{
                background: this.state.color,
                width: 100,
                height: 100
             }}
             onClick = {this.changeColor}
          >
          </div>
      </div>
    );
  }
}

We create a div with a background by passing in an object with the styles in the style prop.

We set the width and height to 100px so that we can display a div with nothing inside.

Then we can pass in a click handler to the onClick prop.

In the changeColor method, we just toggle between white and black for the color state.

Conclusion

We can use onClick with divs if we provide it a size.

Categories
React Answers

How to Sort an Array of Objects in React and Then Render Them?

Sometimes, we want to sort objects that we want to render from an array in a React component before rendering them.

In this article, we’ll look at how to sort objects that we want to render from an array in a React component before rendering them.

Sort an Array of Objects in React and Render Them

We can sort an array of objects with the sort method.

Then we can call map to render the sorted entries.

For instance, in the render method or function component, we may write:

const myData = this.state.data
  .sort((a, b) => a.name > b.name ? 1 : -1)
  .map((item) => (
     <div key={item.id}> {item.name}</div>
  ));

We call the sort method sort the data by the name property.

We check if a.name > b.name is true .

Strings can be compared directly.

Conclusion

We can sort an array of objects with the sort method.

Then we can call map to render the sorted entries.

Categories
React Answers

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

Sometimes, we want to set the active class name for wrapper element of React Router links.

In this article, we’ll look at how to set the active class name for wrapper element of React Router links.

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 create a wrapper element for a link by creating a component.

The activeClassName value can be passed in from the props.

Categories
React Answers

How to Check if a Function is Called on a Component Jest?

Sometimes, we want to check if a function is called when we do something in our React component test.

In this article, we’ll look at how to check if a function is called when we do something in our React component test with Jest.

Check if a Function is Called on a Component Jest

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.

Conclusion

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

Categories
React Answers

How to Automatically Redirect After Login with React Router

Oftentimes, we want to automatically redirect the user to another page after the user logged in.

In this article, we’ll look at how to automatically redirect the user to another page after the user logged in with React Router.

Automatically 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 .

Conclusion

We can automatically redirect after login with React Router.

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