React location.pathname to (custom) title

Viewed 736

I am currently developing in a react project and I want to show the current page title in my header. To currently do this, I am using the props.location.pathname and a switch-case to get the desired output.

This looks something like below.

    var currentPathname = this.props.location.pathname;

    switch (currentPathname) {
        case '/':
            return 'Home';
    }

The amount of paths are adding up and I do not want to make one big switch-case. So I was wondering, if there is any better way to set a (custom) title depending on a path. I expected something to be available in the react-router but I have not found such a thing yet.

Any insights are welcome.

5 Answers

Use a map instead of using switch statement.

const {pathname} = this.props.location;
const pathToTitleMap = {
  "/": "Home",
  "/something": "Amazing page title"
}
document.title = pathToTitleMap[pathname]

I'd say that you don't really have a different option. You'll need some place that maps the path to the title (If your titles cant be retrieved from the path name itself). If you want to make it look a bit shorter, you could use the ternary operator like this:

const path = this.props.location.pathname;
const title = path == '/' ? 'Home' : path == '/contact' ? 'customContactTitle' ...

You could make a hook out of it, like 'getTitle' and then just import it in your pages.

I think your solution looks clean enough. As long as you separate the logic for getting the path and its title into a single file (hook) it should be maintainable since you normally don't add static paths too often.

If you're using Next.js, you could store the paths and their corresponding titles in a database or CMS and then fetch them once during build time (with Next's getStaticProps) if that would help with maintainability.

Have you thought about making the paths equal to or related the title so you would only need to display a custom title once on the index '/' page and otherwise retrieve it from the path?

You can have a map of paths and title

const pathToTitleDictionary = {
    "/": "Home",
    "/about": "About",
    ...
}

function PageTitle({path}) {    
    useEffect(() => {
        document.title = pathToTitleDictionary[path];
    },[path]);
}

Use <PageTitle path={this.props.location.pathname} /> to update the title

You can do it by maintaining a JSON like

var titleForRoutes=[
{
route:"/",          //route 
title:"Home",       //title to show on header
component:HomePage  //React Component
},
{
route:"/Login",
title:"Login", 
component:LoginPage 
}
]

then in routes declare routed by iterating on that Json and on the other hand you can show the title using the same JSON.

Thank you.

I use a custom element to ensure my paths and titles are tidy and next to each other. While a little longer than some of the other answers, it keeps everything inside properties. Could likely be improved by using function component for Page.

<CustomRoute
    path="/path/is/here"
    component={ComponentHere}
    title="Title goes here"
/>

/* * * * * * * * * * * * * * */


export const CustomRoute = ({ component = null, title = null, ...props }) => {
  return (
    <Route
      {...props}
      render={
        props2 => <Page {...props2} component={component} title={title} />
      }
      key={props.path}
    />
  );
};

class Page extends Component {
  componentDidMount() {
    document.title =
      (this.props.title ? this.props.title + ' - ' : '') + 'Website Name';
  }

  render() {
    const { component, ...props } = this.props;
    const PageComponent = component;

    return <PageComponent {...props} />;
  }
}
Related