Categories
React Answers

How to push to history in React Router v4?

Sometimes, we want to push to History in React Router v4.

In this article, we’ll look at how to push to History in React Router v4.

How to push to History in React Router v4?

To push to History in React Router v4, we can use the createBrowserHistory method to return the history object.

Then we can call push on the history object.

For instance, we write

history.js

import {
  createBrowserHistory
} from 'history';

export default createBrowserHistory();

to add a module that returns the history object returned from createBrowserHistory.

Then we add some routes with

app.js

import { Router, Route, Link } from 'react-router-dom';
import history from './history';

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/login">Login</Link></li>
        </ul>
        <Route exact path="/" component={HomePage} />
        <Route path="/login" component={LoginPage} />
      </div>
    </Router>
  </Provider>,
  document.getElementById('root'),
);

And then we can navigate in our code with

actionCreators.js

import history from '../history';

export const login = (credentials) => {
  return async (dispatch) => {
    await loginRemotely(credentials)
    //...
    history.push('/');
  };
}

We call history.push to push to the history and navigate by importing the history object with the import statement and call push on it.

Conclusion

To push to History in React Router v4, we can use the createBrowserHistory method to return the history object.

Then we can call push on the history object.

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 Native Answers

How to add a horizontal FlatList with multiple rows with React Native?

Sometimes, we want to add a horizontal FlatList with multiple rows with React Native

In this article, we’ll look at how to add a horizontal FlatList with multiple rows with React Native.

How to add a horizontal FlatList with multiple rows with React Native?

To add a horizontal FlatList with multiple rows with React Native, we can set the numColumns prop.

For instance, we write:

import * as React from 'react';
import { FlatList, Text, View, Dimensions } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

const flatListItems = Array(200)
  .fill()
  .map((_, i) => ({ title: i, id: i }));

const Item = (item) => {
  const { title } = item;
  return (
    <View
      style={{
        backgroundColor: '#f9c2ff',
        padding: 20,
        marginVertical: 8,
        marginHorizontal: 16,
      }}>
      <Text onPress={() => console.log(item)}>{title}</Text>
    </View>
  );
};

export default function App() {
  const renderItem = ({ item }) => <Item title={item.title} />;
  const keyExtractor = (item) => item.id;

  return (
    <View>
      <FlatList
        style={{ height: 300 }}
        data={flatListItems}
        renderItem={renderItem}
        keyExtractor={keyExtractor}
        numColumns={3}
      />
    </View>
  );
}

to set the numColumns prop of the FlatList to 3.

As a result, we should see 3 columns displayed in the FlatList.

Conclusion

To add a horizontal FlatList with multiple rows with React Native, we can set the numColumns prop.