user8934737
user8934737

Reputation:

how to active menu bar on button click in react?

I'm working on react application.I have create general layout of page which contain sidebar and its working fine and active particular link which is clicked.Now i have created another page which contain button of same nav menu and redirect to specific page which i want.When i clicked on the button the sidebar specific menu is not activated.it activated only when I click on sidebar link.i am using semantic react for this.How can i handle the menu active item for both side.My general layout:

 class SidebarLeftOverlay extends Component {
      state = { visible: false,activeItem: 'home' }

      toggleVisibility = () => this.setState({ visible: !this.state.visible })
       handleItemClick = (e, { name }) => this.setState({ activeItem: name })
      render() {
        const { visible } = this.state
        return (
          <div>
            <Button onClick={this.toggleVisibility}>Toggle Visibility</Button>
            <Sidebar.Pushable as={Segment}>
              <Sidebar as={Menu} animation='overlay' width='thin' visible={visible} icon='labeled' vertical>
                 <Menu pointing secondary vertical>
            <Menu.Item name='home' active={activeItem === 'home'} onClick={this.handleItemClick} />
            <Menu.Item name='messages' active={activeItem === 'messages'} onClick={this.handleItemClick} />
            <Menu.Item name='friends' active={activeItem === 'friends'} onClick={this.handleItemClick} />
          </Menu>
              </Sidebar>
              <Sidebar.Pusher>
                <Segment basic>
                  <Header as='h3'>Application Content</Header>
                  <Image src='/assets/images/wireframe/paragraph.png' />
                </Segment>
              </Sidebar.Pusher>
            </Sidebar.Pushable>
          </div>
        )
      }
    }

My another layout which contain button for same link:

<Button content='message' onClick={() => {this.setState({activeItem:'message})}}/>

I am new to react.How can i set menu item message active on button click as well.??

Upvotes: 0

Views: 2843

Answers (1)

user5699040
user5699040

Reputation:

Add new prop activeItem to SidebarLeftOverlay class:

import PropTypes from 'prop-types'

class SidebarLeftOverlay extends Component {

  state = { visible: false, activeItem: 'home' }

  componentWillReceiveProps(nextProps) {
    const updateActiveItem = nextProps.activeItem && nextProps.activeItem !== this.state.activeItem

    if (updateActiveItem) {
      this.setState({ activeItem: nextProps.activeItem })
    }
  }

...
} // end of class

SidebarLeftOverlay.propTypes = {
  activeItem: PropTypes.string
}

Then, provide props to the class component:

<SidebarLeftOverlay activeItem={this.state.activeItem} />

So when you click at the button your state activeItem changes, and SidebarLeftOverlay will re-render according to new state

Upvotes: 1

Related Questions