Categories
React Answers

How to Disable a React Router if it’s Active

Sometimes, we want to disable a React Router Link if it’s active.

In this article, we’ll look at how to disable a React Router Link if it’s active.

How to Disable an <Link> if it’s Active

We can disable a link by setting the pointer-events attribute in our CSS.

Since we can pass a className attribute with the CSS class to the Link , we can write:

class Foo extends React.Component {
  render() {
    return (
      <Link to='/bar' className='disabled-link'>click me</Link>
    );
  }
}

We have the disabled-link class name applied to the link.

Then we can add the following CSS to disable the link:

.disabled-link {
  pointer-events: none;
}

Conclusion

We can disable a link by setting the pointer-events attribute in our CSS.

Categories
React Answers

How to Redirect to a Different Page with React Router after a Redux Action is Done?

Sometimes, we want to redirect to a different page with React Router after a Redux action is complete.

In this article, we’ll look at how to to redirect to a different page with React Router after a Redux action is complete.

React Router Redirect after Redux Action

We can redirect after a Redux action is committed.

To do that, we install the history package.

We install it by running:

npm install --save history

Then we can create a function like:

import { createBrowserHistory } from 'history';

const browserHistory = createBrowserHistory();

const actionName = () => (dispatch) => {
  axios
    .post('url', { body })
    .then(response => {
       dispatch({
         type: ACTION_TYPE_NAME,
         payload: payload
       });
       browserHistory.push('/foo');
    })
    .catch(err => {
      // Process error code
    });
  });
};

We make a POST request with Axios.

Then in the then callback, we call dispatch to dispatch our actions.

And then we call browserHistory.push to navigate.

We called createBrowserHistory to get the browserHistory object.

Conclusion

We can redirect after a Redux action is committed.

Categories
React Answers

How to Run React Hooks Cleanup Code When Component Unmounts?

Sometimes, we need to clean up resources used in the React useEffect hook when a component unmounts.

In this article, we’ll look at how to clean up resources used in the React useEffect hook when a component unmounts.

Run React Hooks useEffect Cleanup Code When Component Unmounts

We can return a function in the useEffect callback to return a function that runs our clean up code.

For example, we can write:

const { useState, useEffect } = React;

const ForExample = () => {
  const [name, setName] = useState("");
  const [username, setUsername] = useState("");

  useEffect(
    () => {
      console.log("do something");
    },
    [username]
  );

  useEffect(() => {
    return () => {
      console.log("cleaned up");
    };
  }, []);

  const handleName = e => {
    const { value } = e.target;
    setName(value);
  };

  const handleUsername = e => {
    const { value } = e.target;
    setUsername(value);
  };

  return (
    <div>
      <div>
        <input value={name} onChange={handleName} />
        <input value={username} onChange={handleUsername} />
      </div>
    </div>
  );
};

We have our change event handlers.

And we have our useEffect calls.

They all have their own callbacks.

The first one watches for changes in the username function.

In the 2nd one, the callback returns a function that runs code when the component unmounts.

Conclusion

We can return a function in the useEffect callback to return a function that runs our clean up code.

Categories
React Answers

How to Detect a Whether an Entity is React Component or a React Element?

Sometimes, we want to detect whether a React entity is a component or an element.

In this article, we’ll look at how to detect whether a React entity is a component or an element.

Detect a React Component vs. a React Element

We can check if an object is a function component by checking that it’s a function and that it contains the 'return React.createElement' code.

For instance, we can write:

const isFunctionComponent = (component) => {
  return (
    typeof component === 'function' &&
    String(component).includes('return React.createElement')
  )
}

To check for a class component we can check for type 'function' .

And we can check for the isReactComponent property in the component’s prototype .

For example, we can write:

const isClassComponent = (component) => {
  return (
    typeof component === 'function' &&
    !!component.prototype.isReactComponent
  )
}

To check if a variable is a valid element, we can use the React.isValidElement method to do that.

For example, we can write:

const isElement = (element) => {
  return React.isValidElement(element);
}

Conclusion

We can check if an object is a function component by checking that it’s a function and that it contains the 'return React.createElement' code.

Categories
React Answers

How to Fix the Cannot Read Property ‘push’ of undefined With React Router Error?

Sometimes, we’ll encounter the ‘ Cannot Read Property ‘push’ of undefined With React Router’ error in our React components.

In this article, we’ll look at how to fix the ‘ Cannot Read Property ‘push’ of undefined With React Router’ error in our React components.

Fix the Cannot Read Property ‘push’ of undefined With React Router Error

We can use the withRouter higher-order component to make the history object available.

For instance, we can write:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(value) {
    this.props.history.push('/dashboard');
  }

  render() {
    return (
      <div>
        <Route
          exact
          path="/"
          render={() => (
            <div>
              <h1>Welcome</h1>
            </div>
          )}
       />
       <Route
         path="/dashboard"
         render={() => (
           <div>
             <h1>Dashboard</h1>
           </div>
         )}
      />
      <button onClick={this.handleClick} >go to dashboard</button>
    );
  }
}

export default withRouter(App);

We have several routes and a handleClick method to let us go to the dashboard route.

We have the this.props.history.push method because we called withRouter higher-order component with App .

Conclusion

We can use the withRouter higher-order component to make the history object available.