Home  >  Article  >  Web Front-end  >  How to dynamically set the title title in a React project (code)

How to dynamically set the title title in a React project (code)

不言
不言Original
2018-09-25 17:39:434098browse

The content of this article is about how to dynamically set the title (code) in React projects. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In the SPA project built with React, the title of the page is written directly in the entry index.html. When the route switches between different pages, the title will not change dynamically. So how to make the title change dynamically as the route switches?
1. Add the title attribute when defining the route.

    {
        path: "/regularinvestment",
        component: Loadable({
            loader: () => import('./../../business/Regularinvestment/index'),
            loading: PageLoading
        }),
        title: "这是自定义的标题"
    }

2. Get the custom title in the routing index.js and set the page title.

   const RouteWithSubRoutes = route => {
        return (
            <Route
                exact
                path={route.path}
                render={props => {
                    document.title = route.title || "默认title";
                    return <route.component {...props} routes={route.routes}></route.component>
                }}
            />
        );
    };
    
    export default () => {
        return allRouters.map((route, i) => {
            return <RouteWithSubRoutes key={i} {...route}/>
        })
    };

The above is the detailed content of How to dynamically set the title title in a React project (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn