Categories
React Tips

React Tips — SSR, Link Underline, and Authorization Header

Spread the love

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Server-Side Rendering of React Components

We can do server-side rendering with React and React Router.

For instance, we can write:

const Router = require('react-router');
const React = require("react");
const url = require("fast-url-parser");

const routeHandler = (req, res, next) => {
   const path = url.parse(req.url).pathname;
   if (/^/?api/i.test(path)) {
     return next();
   }
   Router.run(routes, path, (Handler, state) => {
     const markup = React.renderToString(<Handler routerState={state} />);
     const locals = { markup };
     res.render("main", locals);
  });
};

app.get('/', routeHandler);
app.listen(3000);

We call Router.run to route the routes for the front end to what we want.

In the Router.run callback, we run React.renderToString to render our Handler component to a static strung.

Then we pass it into the locals object and pass it off to the 'main' template.

Without React Router, we can write:

import React from 'react'
import ReactDOM from 'react-dom/server'
const express = require('express');
const app = express();

const Hello = (props) => {
  return (
    <div>
      <p>hello</p>
    </div>
  )
}

app.get('/', (req, res) => {
  const app = ReactDOM.renderToString(<Hello />)
  const html = `<!doctype html>
    <html>
      <head>${styles}</head>
      <body>
        <div id="root">${app}</div>
      </body>
    </html>`
  res.end(html)
})

app.listen(3000)

We use Express as we did in the previous example, but we removed the Reactv Router part.

We just call ReactDOM.renderToString to render the component to a string.

Then we render it straight as HTML.

In both examples, we can’t add anything dynamic to our components like event handlers or state changes to our components since it’s been rendered as a static string.

If we need all that, then we can use frameworks like Next.js to make adding dynamic features much easier.

Get Rid of Underline for Link Component of React Router

We can get rid of the underline for the Link component by changing some styles.

For instance, we can use styled-components and write:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import styled from 'styled-components';

const StyledLink = styled(Link)`
  text-decoration: none;
  &:focus, &:hover, &:visited, &:link, &:active {
    text-decoration: none;
  }
`;

export default (props) => <StyledLink {...props} />;

We pass in the Link component to the styled tag so that we can style it.

We applied text-decoration: none on the link and all its pseudoclasses to make remove the underline.

If we’re only styling one link, we can also write:

<Link style={{ textDecoration: 'none' }} to="/home">
  Home
</Link>

We pass in an object to the style tag to style it.

We also added textDecoration: 'none' to remove the underline.

Attach Authorization Header for All Axios Requests

If we’re using Axios in our React app, we can add an authorization header to all requests to using its request interceptor feature.

For instance, we can write:

axios.interceptors.request.use((config) => {
  const token = store.getState().token;
  config.headers.Authorization =  token;
  return config;
});

We get the header from a central store and then set that as the value of the Authorization header by setting the returned value as the value of the config.headers.Authorization property.

We can also create our own shared module that calls the Axios requests as follows:

import axios from 'axios';

const httpClient = (token) => {
  const defaultOptions = {
    headers: {
      Authorization: token,
    },
  };

  return {
    get: (url, options = {}) => axios.get(url, { ...defaultOptions, ...options }),
    post: (url, data, options = {}) => axios.post(url, data, { ...defaultOptions, ...options }),
    put: (url, data, options = {}) => axios.put(url, data, { ...defaultOptions, ...options }),
    delete: (url, options = {}) => axios.delete(url, { ...defaultOptions, ...options }),
  };
};

We have a client function that gets the token and returns an object with common HTTP request methods with the request options, which includes the token merged into the options.

Then we can reuse that anywhere:

const request = httpClient('secret');
request.get('http://example.com');

Conclusion

We can do server-side rendering with React, React Router and Express,

To get rid of the underline of a React Router link, we can pass in styles to remove it in various ways.

There are also multiple ways to pass a token to all routes into all Axios requests.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *