简体   繁体   中英

Dynamic header child component in react/redux application

I'm building a react application where the header changes based on the routes, but also depending of the state of other components.

I'm looking for a way to control the header from child components.

For example, I would like that when I click on a button in the main page the header would append new components.

Is there a way to achieve this while avoiding multiple if statements in the header ?

Have a variable in your state which contains the content to be appended to the header. React takes care of reloading all the components when there is a change in the state.

Ex - App.jsx

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { appendHeaderDemo } from 'redux/demo.js'

class ChildComponent1 extends Component {
  render() {
    return <h3>Child component 1 added to header</h3>
  }
};

class ChildComponent2 extends Component {
  render() {
    return <h3>Child component 2 added to header</h3>
  }
};

class App extends Component {
  render() {
    const { dispatch } = this.props

    return (
      <div className='container'>
        <h1> This is my header {this.props.appendToHeader} </h1>

        { this.props.appendToHeader == 'Button clicked' &&
          <ChildComponent1 />
        }

        { this.props.appendToHeader == 'Some Other State' &&
          <ChildComponent2 />
        }

        <button type="button" onClick={ () => onButtonClick() }> Change Header Content </button>

        <div className='container'>
          {this.props.children}
        </div>
      </div>
    );
  };
}

function mapStateToProps(state) {
  const { appendToHeader } = state

  return {
    appendToHeader
  }
}

export default connect(mapStateToProps, { onButtonClick: appendHeaderDemo })(App)

redux/demo.js -

export const CHANGE_HEADER_CONTENT = 'CHANGE_HEADER_CONTENT'

const initialState = {
  appendToHeader: ''
};

// Reducer
export default function appendHeader(state = initialState, action) {
  switch (action.type) {
    case CHANGE_HEADER_CONTENT:
      return Object.assign({}, state, {
        appendToHeader: 'Button clicked'
      })
    default:
      return state
  }
}

// Actions
export function appendHeaderDemo() {
  return {
    type: CHANGE_HEADER_CONTENT
  }
}

Dispatch function appendHeaderDemo can be called from any child and the corresponding changes will be reflected in the header (if there is a change in the state attribute appendToHeader )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM