I have a sidebar that works fine when you click to right button in my navbar, instead of click to button I want to open it when user starts to type in the search input, that because I providing to my component searchInput as prop. With this if statement
if (!!searchInput) {
toggleDrawer("right", true);
}
in my code it should toggle it to open sidebar when users start to type, but nothing happens when I start to type.
import { Fragment, useEffect, useState } from "react";
import Box from "@mui/material/Box";
import Drawer from "@mui/material/Drawer";
import Button from "@mui/material/Button";
import List from "@mui/material/List";
import Divider from "@mui/material/Divider";
import ListItem from "@mui/material/ListItem";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import InboxIcon from "@mui/icons-material/MoveToInbox";
import MailIcon from "@mui/icons-material/Mail";
import { collection, getDocs } from "@firebase/firestore";
import db from "../../firebase";
export default function SearchDrawer({ searchInput }) {
const [messages, setMessages] = useState([]);
const [state, setState] = useState({
right: false,
});
useEffect(() => {
const getMessages = async () => {
const channels = await getDocs(collection(db, "channels"));
channels.forEach(async (channel) => {
const msgs = await getDocs(
collection(db, "channels", channel.id, "messages")
);
msgs.forEach((msg) => {
setMessages((prev) => [...prev, msg.data()]);
});
});
};
return () => setMessages([]) && getMessages();
}, []);
// console.log(messages);
const toggleDrawer = (anchor, open) => (event) => {
if (
event.type === "keydown" &&
(event.key === "Tab" || event.key === "Shift")
) {
return;
}
setState({ ...state, [anchor]: open });
};
if (!!searchInput) {
toggleDrawer("right", true);
}
const list = (anchor) => (
<Box
sx={{ width: anchor === "top" || anchor === "bottom" ? "auto" : "45vw" }}
role="presentation"
onClick={toggleDrawer(anchor, false)}
onKeyDown={toggleDrawer(anchor, false)}
>
<List>
{["Inbox", "Starred", "Send email", "Drafts"].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>
{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
<Divider />
<List>
{["All mail", "Trash", "Spam"].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>
{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
</Box>
);
return (
<>
<Fragment key={"right"}>
<Button onClick={toggleDrawer("right", true)}>{"right"}</Button>
<Drawer
anchor={"right"}
open={state["right"]}
onClose={toggleDrawer("right", false)}
>
{list("right")}
</Drawer>
</Fragment>
</>
);
}
CodePudding user response:
You are returning a function from
if (!!searchInput) {
toggleDrawer("right", true);
}
You could change it to
if(searchInput && !state.right){
setState({right:true})
}