Update the header title based on the page displayed ( sibling component)

Viewed 3340

The App.js component contains a <Header /> and <Page /> component. I want the <h1> to update depending on the Page component. I'm using react-router in the App.js file.

How do I set the title as a prop in each Page component?

For example, the About page component is:

import React, { Component } from 'react';

class About extends Component {

 componentDidMount(){
  this.setState({ title: 'About Us' });
 }

 render() {
  return (
   <div className="about container">
    <p>Page content.</p>  
   </div>
  );
 }
}

export default About;

And the Header component is:

import React, { Component } from 'react';
import Nav from '../Nav';
import About from './components/About';

class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: this.props.title
    };
  }

 render() {
  return (
   <div className="header">
     <h1>{this.state.title}</h1>
     <Nav />
   </div>
  );
 }
}

export default Header;
1 Answers

In short, you can use React Router to get the current pathname in the App.js component. Depending on the current pathname, you can send a prop named "title" to the header, containing the corresponding desired name.

e.g.

getTitle = () => {
    switch(this.props.location.pathname){
        case "about":
            return "About us";
        case "login":
            return "Login to app";
        default:
            return "[APP_NAME]"
    }
}

This way you can catch the current pathname in the parent component, in a single place, keeping your app generic in that manner.

Related