Categories
JavaScript Answers React Answers

How to programmatically navigate using React Router?

Sometimes, we want to programmatically navigate using React Router.

In this article, we’ll look at how to programmatically navigate using React Router.

How to programmatically navigate using React Router?

To programmatically navigate using React Router, we can use the history.push method.

For instance, we write

import {
  useHistory
} from "react-router-dom";

const HomeButton = () => {
  const history = useHistory();

  const handleClick = () => {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      home
    </button>
  );
}

to call the useHistory to return the history object.

Then we call history.push with the URL we want to go to in handleClick to redirect to the URL.

Conclusion

To programmatically navigate using React Router, we can use the history.push method.

Categories
JavaScript Answers React Answers

How to fix React-router URLs don’t work when refreshing or writing manually?

Sometimes, we want to fix React-router URLs don’t work when refreshing or writing manually.

In this article, we’ll look at how to fix React-router URLs don’t work when refreshing or writing manually.

How to fix React-router URLs don’t work when refreshing or writing manually?

To fix React-router URLs don’t work when refreshing or writing manually, we should make sure that we’re redirecting the React app URLs to index.html in our web server.

For instance, in Apache, we add the following to the .htaccess file.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

We intercept all URLs with

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

And then we redirect them to index.html with

RewriteRule . /index.html [L]

Conclusion

To fix React-router URLs don’t work when refreshing or writing manually, we should make sure that we’re redirecting the React app URLs to index.html in our web server.

Categories
JavaScript Answers React Answers

How to simulate a button click in Jest?

Sometimes, we want to simulate a button click in Jest.

In this article, we’ll look at how to simulate a button click in Jest.

How to simulate a button click in Jest?

To simulate a button click in Jest, we can call the simulate method.

For instance, we write:

import React from 'react';
import {
  shallow
} from 'enzyme';
import Button from './Button';

describe('Test Button component', () => {
  it('Test click event', () => {
    const mockCallBack = jest.fn();

    const button = shallow(<Button onClick={mockCallBack}>Ok</Button>);
      button.find('button').simulate('click'); expect(mockCallBack.mock.calls.length).toEqual(1);
    });
  });
})

to call shallow to mount the Button component.

Then we call find with 'button' to find the button element.

And then we call simulate with 'click' to simulate a click on it.

Then we call expect to check that the mockCallBack has been called once by checking mockCallBack.mock.calls.length.

Conclusion

To simulate a button click in Jest, we can call the simulate method.

Categories
JavaScript Answers React React Answers

How to access canvas context in React and JavaScript?

Sometimes, we want to access canvas context in React and JavaScript.

In this article, we’ll look at how to access canvas context in React and JavaScript.

How to access canvas context in React and JavaScript?

To access canvas context in React and JavaScript, we can assign a ref to the canvas and call getContext on the ref’s value.

For instance, we write:

import React from "react";

export default function App() {
  const ref = React.useRef();
  console.log(ref.current.getContext("2d"));

  return (
    <>
      <canvas ref={ref} />
    </>
  );
}

to call useRef to create a ref.

Then we get the context by calling ref.current.getContext with '2d' to get the context.

Conclusion

To access canvas context in React and JavaScript, we can assign a ref to the canvas and call getContext on the ref’s value.

Categories
JavaScript Answers React React Answers

How to detect network connection in a JavaScript React app, and if offline, hide a component from user?

Sometimes, we want to detect network connection in a JavaScript React app, and if offline, hide a component from user.

In this article, we’ll look at how to detect network connection in a JavaScript React app, and if offline, hide a component from user.

How to detect network connection in a JavaScript React app, and if offline, hide a component from user?

To detect network connection in a JavaScript React app, and if offline, hide a component from user, we can listen to the online and offline events.

For instance, we write:

import React from "react";

export default function App() {
  const [online, setOnline] = React.useState(navigator.onLine);

  const onNetworkStatusChange = () => {
    setOnline(navigator.onLine);
  };

  React.useEffect(() => {
    window.addEventListener("online", onNetworkStatusChange);
    window.addEventListener("offline", onNetworkStatusChange);

    return () => {
      window.removeEventListener("online", onNetworkStatusChange);
      window.removeEventListener("offline", onNetworkStatusChange);
    };
  }, []);

  return <>{online ? <div>online</div> : <div>offline</div>}</>;
}

to call window.addEventListener with 'online' and 'offline' to listen for the online and offline events.

online event is emitted when the device is online and the offline event is emitted otherwise.

We set the event listener of each event to onNetworkStatusChange.

In it, we call setOnline with navigator.onLine to set the value of online.

navigator.onLine is true if the device is online and false otherwise.

We also call removeEventListener in the function we return in the useEffect callback to remove the listeners once the component is unmounted.

Then when the device is online we display ‘online’.

Otherwise, we display ‘offline’.

Conclusion

To detect network connection in a JavaScript React app, and if offline, hide a component from user, we can listen to the online and offline events.