Categories
React Answers

How to pass parameters with history.push, Link, or Redirect in React Router v4?

Sometimes, we want to pass parameters with history.push, Link, or Redirect in React Router v4.

In this article, we’ll look at how to pass parameters with history.push, Link, or Redirect in React Router v4.

How to pass parameters with history.push, Link, or Redirect in React Router v4?

To pass parameters with history.push, Link, or Redirect in React Router v4, we can set the state property.

For instance, we write

this.props.history.push({
  pathname: '/template',
  search: '?query=abc',
  state: {
    detail: response.data
  }
})

to call history.push with an object with the state property to pass props to the history object.

With the Link, component, we write

<Link
  to={{
    pathname: "/template",
    search: "?query=abc",
    state: { detail: response.data },
  }}
>
  My Link
</Link>

to set the to prop to an object with the state property containing the data that we want to pass into the route component as props.

Conclusion

To pass parameters with history.push, Link, or Redirect in React Router v4, we can set the state property.

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

How to send custom data along with handshake data in socket.io?

Sometimes, we want to send custom data along with handshake data in socket.io.

In this article, we’ll look at how to send custom data along with handshake data in socket.io.

How to send custom data along with handshake data in socket.io?

To send custom data along with handshake data in socket.io, we can call io with an object with the custom data we want to send as the 2nd argument on client side.

For instance, on client side, we write

const socket = io("http://127.0.0.1:3000/", {
  query: "foo=bar"
});

to call io to create the connection.

Then on server side, we write

io.use((socket, next) => {
  console.log(socket.handshake.query);
  if (socket.handshake.query.foo === "bar") {
    return next();
  }
  next(new Error('Authentication error'));
});

to call io.use with a callback to listen for handshakes.

And we get the value of the query property of the object we called io with on client side with socket.handshake.query.

Conclusion

To send custom data along with handshake data in socket.io, we can call io with an object with the custom data we want to send as the 2nd argument on client side.