Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  21] [ 7]  / answers: 1 / hits: 31532  / 4 Years ago, wed, december 2, 2020, 12:00:00

I'm new in React Frontend developing. I'm trying to add a temporary drawer to my Material-UI NavBar. I've add a drawer in my code:


class Navbar extends Component {
render() {
const { authenticated } = this.props;
const [open, setOpen] = useState(false);
const handleDrawer = () =>{
setOpen(true)
}
return (
<AppBar position="fixed">
<Toolbar className="nav-container">
{authenticated ? (
<Fragment>
<IconButton edge="start" onClick={handleDrawer} >
<Menu/>
</IconButton>
<Drawer
anchor='left'
open={open}
onClose={()=> setOpen(false)}
>
<h3> Drawer</h3>
</Drawer>
<NewPost/>
<Link to="/">
<MyButton tip="Home">
<HomeIcon color = "disabled"/>
</MyButton>
</Link>
<Link to="/chats">
<MyButton tip="Chats">
<ChatIcon color = "disabled"/>
</MyButton>
</Link>
<Notifications />
</Fragment>


):(
<Fragment>
<Button color="inherit" component={Link} to="/login">Login</Button>
<Button color="inherit" component={Link} to="/signup">Singup</Button>
<Button color="inherit" component={Link} to="/">Home</Button>
{/* <Button color="inherit" component={Link} to="/user">Profile</Button>*/}
</Fragment>
)}
</Toolbar>
</AppBar>


)
}
}

Navbar.propTypes = {
authenticated: PropTypes.bool.isRequired
}

const mapStateToProps = state =>({
authenticated: state.user.authenticated
})

export default connect(mapStateToProps)(Navbar)

But this error appeared:


React Hook "useState" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function

So, I've create a constructor to handle this (before render):


constructor(props) {
super(props);
this.state = {
open: false
};
}

And when I want to change the state, I've use:


this.setState({ open: true })

But, when I triggered the Drawer (clicking the button),It does not open. What can I do?


More From » reactjs

 Answers
10

The state hook (useState) is available with functional React Components, but in your case you are using a Class component. Functional React components normally don't have states out of the box, but useState is a new feature that will let you work around that


You can either change this to functional component, or keep it as a class component and use the state differently
E.g :



  • !this.state.open instead of !open
    and

  • this.setState({open: false}) instead of setOpen(false)


https://reactjs.org/docs/hooks-state.html


[#50510] Tuesday, November 17, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleew

Total Points: 70
Total Questions: 87
Total Answers: 117

Location: Namibia
Member since Mon, Feb 21, 2022
2 Years ago
;