'State, Reload Page and URL
When I reload the page I can not display the text corresponding to the current url
I have a Main component that returns a MiniDrawer component, inside of which is NavLink and then routing on the Route components
class Main extends React.Component {
render() {
return (
<BrowserRouter>
<MiniDrawer />
<main>
<Route exact path="/cats" component={<Cats />}/>
<Route path="/dogs" component={<Dogs />}/>
</main>
</BrowserRouter>
)
}
}
Inside the MiniDrawer component, the AppBar comes first, then a ListItem with a NavLink. My problem is that the information displayed on the AppBar depends on the current ListItem, and when I reboot, it displays non-porous information that does not correspond to the current ListItem.
class MiniDrawer extends React.Component {
state={appBarTitle: "Meow-Meow", clickedItem: ""}
handleOnClick = (e, item) => {
this.setState({clickedItem: item.id})
let headerKey = e.currentTarget.innerText
let headerTitle = ""
switch(headerKey) {
case "Cats": headerTitle="Meow-Meow"; break;
case "Dogs": headerTitle="Bow-Wow"; break;
case default: break;
}
this.setState({appBarTitle: headerTitle})
}
render() {
return (
<div>
<AppBar position="fixed">
<Toolbar>
<Typography variant="h6" noWrap>
{this.state.appBarTitle}
</Typography>
</Toolbar>
</AppBar>
<Drawer>
<DrawerHeader>
<SearchInput placeholder="Search pet" />
</DrawerHeader>
<Divider />
<NavMenuList
onClick={this.handleOnClick}
clickedItem={this.state.clickedItem}
/>
</Drawer>
</div>
)
}
}
The navigation list has this structure
const petList = [
{
id: 0,
route: "/cats",
text: "Cats",
tooltip: "Cats"
},
{
id: 1,
route: "/dogs",
text: "Dogs",
tooltip: "Dogs"
}
]
class NavMenuList extends React.Component {
return (
<List>
{petList.map((pet, i) => {
const {id, route, text, tooltip} = pet;
return (
<Tooltip key={text} title={tooltip} placement="top">
<ListItem
button
key={text}
name={text}
component={NavLink}
to={route}
activeClassName={classes.listItemClicked}
onClick={(e) => this.props.onClick(e, pet)}
>
<ListItemIcon>{i%2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
</Tooltip>
)
})}
</List>
)
}
NavLink component from react-router-dom, current pet works on activeClassName props on reboot, but this.state.appBarTitle is reset
Solution 1:[1]
Solved this problem (component MiniDrawer):
state={appBarTitle: "", clickedItem: ""}- Caught url on Vanilla js:
componentDidMount = () => {
let headerTitle = ""
switch(window.location.pathname) {
case "Cats": headerTitle="Meow-Meow"; break;
case "Dogs": headerTitle="Bow-Wow"; break;
default: break;
}
this.setState({appBarTitle: headerTitle});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tims |
