I've build small SPA in React using Semantic UI React. Menu is working as it should and when I click on any of the menu items, it takes me where its supposed to.
The problem is that, if I go to a page/Route and from there change my page/Route to another one, active field in pointing Menu stays pointing at the previous page.
Everything is imported the way it should. I just want to find the way for my menu to always point at the appropriate Route that is currently shown.
Here is my code:
render() {
const { activeItem } = this.state
return (
<div>
<BrowserRouter>
<div>
<Menu pointing>
<Menu.Item name='Home' as={Link} to='/home' active={activeItem === 'Home'} onClick={this.handleItemClick} />
<Menu.Item name='Regions' as={Link} to='/regions' active={activeItem === 'Regions'} onClick={this.handleItemClick} />
<Menu.Item name='Countries' as={Link} to='/countries' active={activeItem === 'Countries'} onClick={this.handleItemClick} />
<Menu.Item name='AllCountries' as={Link} to='/allcountries' active={activeItem === 'AllCountries'} onClick={this.handleItemClick} />
<Menu.Menu position='left'>
<Menu.Item>
<Form.Group onSubmit={this.submit}>
<Input placeholder='Search...' value={this.state.searchTerm} onChange={this.takeTerm} onKeyPress={this.showData}/>
<Link to="/countrydata"><Button type="submit" circular icon="search" /></Link>
</Form.Group>
</Menu.Item>
</Menu.Menu>
<Button.Group>
<Button>English</Button>
<Button.Or text="or"/>
<Button>Francais</Button>
<Button.Or text="or"/>
<Button>Italiano</Button>
</Button.Group>
</Menu>
<Segment>
<Switch>
<Route path="/regions" component={Regions}/>
<Route path="/countries" component={Countries}/>
<Route path="/allcountries" component={AllCountries}/>
<Route path="/countrydata" component={Country} />
<Route path="/" component={Home} />
</Switch>
</Segment>
{this.state.notFound ? (<div className="showError">Searched country does not exist</div>) : <div></div>}
</div>
</BrowserRouter>
</div>
)
} }
I had the same problem today or, at least, a similar one. So I resolved my problem by replacing Link with NavLink and by removing Semantic's "handleItemClick". We don't need Semantic to handle active Menu.Item since react-router can do this with NavLink.
<Menu.Item name='Countries' as={NavLink} to='/countries' />