How do I remove black borders on a pop-up box? - reactjs

I am using material UI and I think the default import of component has black borders. I want to make it so the box is all white with no black borders. Is there a code snippet I can addon to my code to make the black borders go away?
Current outcome
Desired outcome, see how there are no black borders?
code
import { Avatar, IconButton } from '#material-ui/core';
import React, { useEffect, useState } from 'react';
import './Sidebar.css';
import SearchIcon from '#material-ui/icons/Search';
import { RateReviewOutlined } from '#material-ui/icons';
import { SidebarChat } from './SidebarChat';
import { useSelector } from 'react-redux';
import { selectUser } from './features/userSlice';
import db, { auth } from './firebase';
import { makeStyles } from '#material-ui/core/styles';
import Modal from '#material-ui/core/Modal';
import Backdrop from '#material-ui/core/Backdrop';
import Fade from '#material-ui/core/Fade';
import Card from '#material-ui/core/Card';
import CardActionArea from '#material-ui/core/CardActionArea';
import CardActions from '#material-ui/core/CardActions';
import CardContent from '#material-ui/core/CardContent';
import Button from '#material-ui/core/Button';
import Typography from '#material-ui/core/Typography';
const useStyles = makeStyles((theme) => ({
modal: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
root: {
maxWidth: 345,
},
media: {
height: 140,
},
}));
export function Sidebar(props) {
const user = useSelector(selectUser);
const [chats, setChats] = useState([]);
const [filterChats, setFilteredChats] = useState([]);
const classes = useStyles();
const [search, setSearch] = useState('');
const [open, setOpen] = useState(false);
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
useEffect(() => {
db.collection('chats').onSnapshot((snapshot) =>
setChats(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
)
);
db.collection('chats').onSnapshot((snapshot) =>
setFilteredChats(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
)
);
}, []);
const addChat = () => {
const chatName = prompt('Please enter a chat name');
if (chatName) {
db.collection('chats').add({
chatName: chatName,
});
}
};
const searchFunction = (e) => {
setSearch(e);
const filtered = chats.filter(chat => {
return chat.data.chatName.toLowerCase().includes(e.toLowerCase())
});
setFilteredChats(filtered);
};
return (
<div className="sidebar">
<div className="sidebar__header">
<Avatar
onClick={handleOpen}
src={user.photo}
className="sidebar__avatar"
/>
<div className="sidebar__input">
<SearchIcon />
<input
placeholder="Search"
value={search}
onChange={(e) => searchFunction(e.target.value)}
/>
</div>
<IconButton variant="outlined" className="sidebar__inputButton">
<RateReviewOutlined onClick={addChat} />
</IconButton>
</div>
<div className="sidebar__chats">
{filterChats.map(({ id, data: { chatName } }) => (
<SidebarChat key={id} id={id} chatName={chatName} />
))}
</div>
<Modal
style={{border: '2px solid #FFFFFF',}}
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={open}
onClose={handleClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500,
}}
>
<Fade in={open}>
<Card className={classes.root}>
<CardActionArea>
<CardContent>
<Typography gutterBottom variant="h5" component="h2">
{user.displayName.split(' ').slice(0,1).join(' ')},
</Typography>
<Typography variant="body2" color="textSecondary" component="p">
Are you sure you want to sign out?
</Typography>
</CardContent>
</CardActionArea>
<CardActions>
<Button onClick={() => auth.signOut()} size="small" color="primary">
Yes
</Button>
<Button onClick={handleClose} size="small" color="primary">
No
</Button>
</CardActions>
</Card>
</Fade>
</Modal>
</div>
);
}

answer below - switched material ui from Modal to Dialog
import { Avatar, IconButton } from '#material-ui/core';
import React, { useEffect, useState } from 'react';
import './Sidebar.css';
import SearchIcon from '#material-ui/icons/Search';
import { RateReviewOutlined } from '#material-ui/icons';
import { SidebarChat } from './SidebarChat';
import { useSelector } from 'react-redux';
import { selectUser } from './features/userSlice';
import db, { auth } from './firebase';
import { makeStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
import Dialog from '#material-ui/core/Dialog';
import DialogActions from '#material-ui/core/DialogActions';
import DialogContent from '#material-ui/core/DialogContent';
import DialogContentText from '#material-ui/core/DialogContentText';
import DialogTitle from '#material-ui/core/DialogTitle';
export function Sidebar(props) {
const user = useSelector(selectUser);
const [chats, setChats] = useState([]);
const [filterChats, setFilteredChats] = useState([]);
const [search, setSearch] = useState('');
const [open, setOpen] = useState(false);
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
useEffect(() => {
db.collection('chats').onSnapshot((snapshot) =>
setChats(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
)
);
db.collection('chats').onSnapshot((snapshot) =>
setFilteredChats(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
)
);
}, []);
const addChat = () => {
const chatName = prompt('Please enter a chat name');
if (chatName) {
db.collection('chats').add({
chatName: chatName,
});
}
};
const searchFunction = (e) => {
setSearch(e);
const filtered = chats.filter(chat => {
return chat.data.chatName.toLowerCase().includes(e.toLowerCase())
});
setFilteredChats(filtered);
};
return (
<div className="sidebar">
<div className="sidebar__header">
<Avatar
onClick={handleOpen}
src={user.photo}
className="sidebar__avatar"
/>
<div className="sidebar__input">
<SearchIcon />
<input
placeholder="Search"
value={search}
onChange={(e) => searchFunction(e.target.value)}
/>
</div>
<IconButton variant="outlined" className="sidebar__inputButton">
<RateReviewOutlined onClick={addChat} />
</IconButton>
</div>
<div className="sidebar__chats">
{filterChats.map(({ id, data: { chatName } }) => (
<SidebarChat key={id} id={id} chatName={chatName} />
))}
</div>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{`${user.displayName.split(' ').slice(0,1).join(' ')},`}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Are you sure you want to sign out?
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => auth.signOut()} color="primary">
Yes
</Button>
<Button onClick={handleClose} color="primary" autoFocus>
No
</Button>
</DialogActions>
</Dialog>
</div>
);
}

Related

setState (In react functional component) is not updating the existing state in react todo app

I have to do app using react and material ui which is combined of these components:
1- App.js
`
import './App.css';
import Header from './components/Header'
import ToDoApp from './components/ToDoApp';
function App() {
return (
<div className="App">
<Header />
<ToDoApp />
</div>
);
}
export default App;
`
2- ToDoApp.js
`
import React from 'react'
import ToDoList from './ToDoList';
import Task from './Task';
import { Container, Grid } from '#mui/material';
import {useState, } from 'react';
export default function ToDoApp() {
const [todos, setTodos] = useState([
{
id: 1,
Title: "Task 1",
done: true
},
{
id: 2,
Title: "Task 2",
done: true
},
])
const deleteTask = (id) => {
// console.log(id);
const newtodos = todos.filter(function(todo) {
return todo.id !== id;
})
setTodos(newtodos);
}
const addTodo = (todoTitle) => {
const lastTodo = todos[todos.length-1];
const newtodosId = lastTodo.id + 1;
const newtodos = todos;
newtodos.push({
id: newtodosId,
title: todoTitle,
done: false,
})
setTodos(newtodos);
console.log(newtodos);
}
return (
<Container maxWidth="sm">
<Grid item xs={12} md={6}>
<ToDoList newTodo={addTodo}/>
<Task ToDoAppList={todos} DeleteTodoTask={deleteTask}/>
</Grid>
</Container>
)
}
`
3- ToDoList.js
`
import * as React from 'react';
import FormControl from '#mui/material/FormControl';
import Typography from '#mui/material/Typography';
import TextField from '#mui/material/TextField';
import IconButton from '#mui/material/IconButton';
import { Add, AddToDriveOutlined } from '#mui/icons-material/';
import { useState } from 'react';
import { useEffect } from 'react';
export default function ToDoList(props) {
const addTodo = props.newTodo
const [todo, setTodo] = useState('')
function writeTodo(e) {
// console.log(e.target.value);
setTodo(e.target.value);
}
const addText = (e) => {
e.preventDefault();
addTodo(todo);
// console.log(todo);
}
return (
<>
<Typography sx={{ mt: 4, mb: 2 }} variant="h6" component="div">
ToDo List
</Typography>
<form onSubmit={(e) => addText(e)}>
<FormControl>
<div
style={{display: 'flex', marginBottom: 20}}>
<TextField
id="standard-helperText"
label="New ToDo"
style={{ width: 450 }}
variant="standard"
value={todo}
onChange={(e) => writeTodo(e)}
/>
<IconButton edge="end" aria-label="create" type="submit">
<Add />
</IconButton>
</div>
</FormControl>
</form>
</>
)
}
`
4-Task.js
`
import React from 'react'
import Paper from '#mui/material/Paper';
import IconButton from '#mui/material/IconButton';
import { Tag, Check, Delete } from '#mui/icons-material';
export default function Task(props) {
const tasks = props.ToDoAppList;
const deleteTask = props.DeleteTodoTask;
const List = tasks.map(task => { return(
<Paper elevation={3} style={{padding: 10, marginTop: 10}} key={task.id}>
<IconButton aria-label="create">
<Tag />
</IconButton>
<span style={{textDecoration: 'line-through'}}>{task.Title}</span>
<IconButton aria-label="delete" style={{float: 'right', color: 'red'}} onClick={()=>deleteTask(task.id)}>
<Delete />
</IconButton>
<IconButton aria-label="check" style={{float: 'right'}}>
<Check />
</IconButton>
</Paper>
)})
return (
<>
{List}
</>
)
}
`
When Submitting the new Todo, the result is not shown on the DOM.
In the ToDoApp.js -> function "addTodo" I used setState to push the new array with the new item, and is sent to ToDoList.js -> form "onSubmit" event in "addText" function. I put the console.log in the function and I am getting the new array but it's not showing on the page.
The tasks listing is handled in the task.js by sending the array through props and using map function to loop over the array.
Note: I handled the delete function in the ToDoApp.js and it's woking with no problem. I don't understand why it's not running with "addTodo" funciton.
First you need to change title to Title (based on your state Schema)
then you dont need to update whole state just add your new task to your current state (function in setTodos)
const addTodo = (todoTitle) => {
const lastTodo = todos[todos.length - 1];
const newtodosId = lastTodo.id + 1;
let newTodo = {
id: newtodosId,
Title: todoTitle,
done: false
};
setTodos((prev)=>[...prev,newTodo])
};

Trying to use props in order to display new comments (React JS)

I am trying to display new comments instantly when they are created. Currently, it doesn't work.
This is me code. On my PostPage, I added "fetchComments={fetchComments}" to my CommentForm tag. And on my CommentForm, I used props.fetchComments() in the handleSubmit.
Do you have a solution for this ?
My PostPage (parent component) :
import React, { useEffect, useState } from 'react'
import { useParams, Link } from 'react-router-dom'
import { API_URL } from '../config'
import { Skeleton } from '#material-ui/lab'
import { Grid, Button } from '#material-ui/core'
import { AiFillCaretLeft } from "react-icons/ai"
import List from '#material-ui/core/List'
import ListItem from '#material-ui/core/ListItem'
import ListItemText from '#material-ui/core/ListItemText'
import ListItemAvatar from '#material-ui/core/ListItemAvatar'
import Avatar from '#material-ui/core/Avatar'
import Typography from '#material-ui/core/Typography'
import CommentForm from '../Components/Forms/CommentForm'
import PostsAPI from '../Services/PostsAPI'
import CommentsAPI from '../Services/CommentsAPI'
export default function PostPage() {
const {id} = useParams()
const [post, setPost] = useState(null)
const [isLoading, setIsLoading] = useState(false)
const [comments, setComments] = useState([])
const fetchPost = async () => {
const data = await PostsAPI.findOne(id);
setPost(data)
setIsLoading(true)
}
const fetchComments = async (props) => {
try{
const comments = await CommentsAPI.findAll()
setComments(comments.data)
} catch (error) {
console.log(error)
}
}
useEffect(() => {
fetchPost();
fetchComments();
}, [])
return (
<div>
<nav>
<Link to="/">
<Button variant="contained" color="primary"><AiFillCaretLeft /><span>Back</span></Button>
</Link>
</nav>
<Grid container spacing = {2}>
<Grid item sm={6}>
<div className='postImg'>
{isLoading ? <img src={API_URL + post.data.attributes.image.data[0].attributes.formats.small.url} alt={post.data.attributes.title} /> : <Skeleton variant="rect" width="100%" height={400} />}
</div>
</Grid>
<Grid item sm={6}>
<h1>{isLoading ? post.data.attributes.title : <Skeleton variant="text" width={300} height={80} />}</h1>
<p>{isLoading ? post.data.attributes.content :
<>
<Skeleton variant="text" height={25}/>
<Skeleton variant="text" width="60%" height={25}/>
</>
}</p>
</Grid>
</Grid>
<Grid container spacing={2}>
<Grid item md={6}>
<CommentForm fetchComments={fetchComments} />
</Grid>
<Grid item md={6}>
{<List>
{comments.map((comment, i) => (
<ListItem key={i} alignItems="flex-start">
<ListItemAvatar>
<Avatar alt="Avatar" src="/static/images/avatar/1.jpg" />
</ListItemAvatar>
<ListItemText
primary={comment.attributes.pseudo}
secondary={
<React.Fragment>
<Typography
component="span"
variant="body2"
color="textPrimary"
>
</Typography>
"{comment.attributes.content}"
</React.Fragment>
}
/>
</ListItem>
))}
</List>}
</Grid>
</Grid>
</div>
)
}
The CommentForm (child component) :
import React, { useState } from 'react'
import { useParams } from 'react-router-dom'
import TextField from '#material-ui/core/TextField';
import { Button } from '#material-ui/core'
import CommentsAPI from '../../Services/CommentsAPI'
export default function CommentForm(props) {
const [comment, setComment] = useState({})
const {id} = useParams()
const handleSubmit = async (event) => {
event.preventDefault();
try {
CommentsAPI.create(JSON.parse(`{"data":${JSON.stringify(comment)}}`));
props.fetchComments()
} catch (error) {
console.log(error)
}
}
const handleChange = (event) => {
const {name, value} = event.currentTarget
setComment({
...comment,
[name]: value,
"post":id
})
}
return (
<form onSubmit={handleSubmit}>
<div>
<TextField
id="pseudo"
label="Pseudo"
type="text"
onChange={handleChange}
name="pseudo"
/>
</div>
<div>
<TextField
id="comment"
label="Comment"
multiline
minRows={2}
onChange={handleChange}
name="content"
/>
</div>
<div>
<Button variant="contained" color="primary" type="submit">
Send
</Button>
</div>
</form>
)
}
Thank you for your help !
You can do something like this.
const [apiData, setAPIData] = useState();
const handleSubmit = async (event) => {
event.preventDefault();
try {
CommentsAPI.create(JSON.parse(`{"data":${JSON.stringify(comment)}}`));
const data = await props?.fetchComments();
//--
setAPIData(data);
} catch (error) {
console.log(error)
}
}
return (
{ data.map( item => {----} )
}
)
Thanks.
~ Storm In Talent

Adding Validation and Function to Input using React and MUI

I am creating a cat APP, that pulls a request from thecatapi, I want my submit button to load my ImageGrid.jsx when they input the correct link for example:
in the dialog box you put:
https://api.thecatapi.com/v1/images/search
then it must have a submit loading function and take you to the images of the cats:
what i have is this:
import React, { useState } from 'react';
import PropTypes from 'prop-types'
import getCat from './ImageGrid'
// Material UI
import DialogActions from '#material-ui/core/DialogActions';
import DialogContent from '#material-ui/core/DialogContent';
import DialogTitle from '#material-ui/core/DialogTitle';
import Input from '#material-ui/core/Input'
import Dialog from '#material-ui/core/Dialog';
import Button from '#material-ui/core/Button';
import Grid from '#material-ui/core/Grid';
const DialogBox = ({ ariaLabel }) => {
const [open, setOpen] = React.useState(false);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
// const handleGrid = () => {
// React.useState(true)
// }
return (
<div className='modal'>
<Grid container justifyContent='center'>
{/* Button To Open Dialog Box */}
<Button
style={{border: '1px solid #ebc340', color: '#ebc340'}}
variant="outlined"
color="secondary"
onClick={handleClickOpen}>
Welcome to my Case Study, Click to begin
</Button>
</Grid>
{/* Dialog Box Content */}
<Dialog
className='dialog-btn'
open={open}
onClose={handleClose}>
<DialogTitle>
To begin the application, please insert your URL below:
</DialogTitle>
<DialogContent>
<Input
placeholder="Enter Your Link Here"
inputProps={ariaLabel}
fullWidth/>
</DialogContent>
{/* Dialog Box Actions */}
<DialogActions>
<Button
onClick={handleClose}
color="secondary">
Cancel
</Button>
<Button
onClick={ getCat }
color='primary'
autoFocus
type='submit'>
{/* onSubmit={handleGrid} */}
Submit
</Button>
</DialogActions>
</Dialog>
</div>
);
}
Input.inputProps = {
ariaLabel: 'Please insert your URL below',
tertiaryColor: 'tertiary'
}
Input.inputTypes = {
ariaLabel: PropTypes.string.isRequired,
tertiaryColor: PropTypes.string.isRequired,
};
export default DialogBox
and then it needs to load this:
/
/ Fetch data from
import React, { useCallback, useEffect, useState } from "react";
const url = "https://api.thecatapi.com/v1/images/search?limit=9";
function ImageGrid() {
const [catUrls, setCatUrls] = useState();
const getCat = useCallback(() => {
console.log("Hello World");
let catImageUrlList = [];
// fetch http request
fetch(url)
.then((res) => res.json()) //gives data in json
.then((cats) => {
console.log("Cats: ", cats);
for (let i = 0; i < cats.length; i++) {
catImageUrlList.push(cats[i].url);
}
setCatUrls(catImageUrlList);
})
.catch((error) => {
console.log("Error: ", error);
});
}, [setCatUrls]);
useEffect(() => {
console.log("Loading your feline friends....");
getCat();
}, [getCat]);
return (
<>
<h1>Look At These Beautiful Kitty's!</h1>
{catUrls ? (
catUrls.map((catUrl) => <img src={catUrl} alt={"kitty"} />)
) : (
<p>Loading...</p>
)}
<button onClick={getCat}>Refresh</button>
</>
);
}
export default ImageGrid;

I have a search bar that wont update whenever I press backspace

So I have a basic messenger chap application, the search bar to retrieve chats works fine whenever I type in letters, yet whenever I backspace, the event handler wont update, and I am left with the chat room lists that fit the search, even though the search bar is left empty.
Examples below
1.All chatrooms are shown below:
2.Typing "funny" filters a list with chatrooms labeled "funny":
3.Pressing backspace does not show all the chatrooms:
import { Avatar, IconButton } from '#material-ui/core';
import React, { useEffect, useState } from 'react';
import './Sidebar.css';
import SearchIcon from '#material-ui/icons/Search';
import { RateReviewOutlined } from '#material-ui/icons';
import { SidebarChat } from './SidebarChat';
import { useSelector } from 'react-redux';
import { selectUser } from './features/userSlice';
import db, { auth } from './firebase';
import { makeStyles } from '#material-ui/core/styles';
import Modal from '#material-ui/core/Modal';
import Backdrop from '#material-ui/core/Backdrop';
import Fade from '#material-ui/core/Fade';
const useStyles = makeStyles((theme) => ({
modal: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
paper: {
backgroundColor: theme.palette.background.paper,
border: '2px solid #000',
boxShadow: theme.shadows[5],
padding: theme.spacing(2, 4, 3),
},
}));
export function Sidebar(props) {
const user = useSelector(selectUser);
const [chats, setChats] = useState([]);
const classes = useStyles();
const [open, setOpen] = useState(false);
const [search, setSearch] = useState('');
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
useEffect(() => {
db.collection('chats').onSnapshot((snapshot) =>
setChats(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
)
);
}, []);
const addChat = () => {
const chatName = prompt('Please enter a chat name');
if (chatName) {
db.collection('chats').add({
chatName: chatName,
});
}
};
const searchFunction = (e) => {
setSearch(e);
console.log(search);
console.log(chats);
const filtered = chats.filter(chat => {
return chat.data.chatName.toLowerCase().includes(e.toLowerCase())
});
// console.log(filtered)
setChats(filtered);
};
return (
<div className="sidebar">
<div className="sidebar__header">
<Avatar
onClick={handleOpen}
src={user.photo}
className="sidebar__avatar"
/>
<div className="sidebar__input">
<SearchIcon />
<input
placeholder="Search"
value={search}
onChange={(e) => searchFunction(e.target.value)}
/>
</div>
<IconButton variant="outlined" className="sidebar__inputButton">
<RateReviewOutlined onClick={addChat} />
</IconButton>
</div>
<div className="sidebar__chats">
{chats.map(({ id, data: { chatName } }) => (
<SidebarChat key={id} id={id} chatName={chatName} />
))}
</div>
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={open}
onClose={handleClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500,
}}
>
<Fade in={open}>
<div className={classes.paper}>
<h2 id="transition-modal-title">
Are you sure you want to sign out?
</h2>
<button onClick={() => auth.signOut()}>Yes</button>
<button onClick={handleClose}>No</button>
</div>
</Fade>
</Modal>
</div>
);
}
In your searchFunction it is constantly updating filtered to have less and less chatrooms. You could store chat rooms as a separate state and then filter that instead to preserve all chat rooms.

I have a simple messenger app with a search bar that wont update the filter whenever I press backspace

So I have a basic messenger chat application with a search bar to retrieve chatrooms, and it works fine whenever I type in letters, yet whenever I backspace, why wont it retrieve the list I had previous?
Examples below
1.All chatrooms are shown below:
2.Typing "funny" filters a list with chatrooms labeled "funny":
3.Pressing backspace does not show all the chatrooms:
import { Avatar, IconButton } from '#material-ui/core';
import React, { useEffect, useState } from 'react';
import './Sidebar.css';
import SearchIcon from '#material-ui/icons/Search';
import { RateReviewOutlined } from '#material-ui/icons';
import { SidebarChat } from './SidebarChat';
import { useSelector } from 'react-redux';
import { selectUser } from './features/userSlice';
import db, { auth } from './firebase';
import { makeStyles } from '#material-ui/core/styles';
import Modal from '#material-ui/core/Modal';
import Backdrop from '#material-ui/core/Backdrop';
import Fade from '#material-ui/core/Fade';
const useStyles = makeStyles((theme) => ({
modal: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
paper: {
backgroundColor: theme.palette.background.paper,
border: '2px solid #000',
boxShadow: theme.shadows[5],
padding: theme.spacing(2, 4, 3),
},
}));
export function Sidebar(props) {
const user = useSelector(selectUser);
const [chats, setChats] = useState([]);
const classes = useStyles();
const [open, setOpen] = useState(false);
const [search, setSearch] = useState('');
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
useEffect(() => {
db.collection('chats').onSnapshot((snapshot) =>
setChats(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
)
);
}, []);
const addChat = () => {
const chatName = prompt('Please enter a chat name');
if (chatName) {
db.collection('chats').add({
chatName: chatName,
});
}
};
const searchFunction = (e) => {
setSearch(e);
console.log(search);
console.log(chats);
const filtered = chats.filter(chat => {
return chat.data.chatName.toLowerCase().includes(e.toLowerCase())
});
// console.log(filtered)
setChats(filtered);
};
return (
<div className="sidebar">
<div className="sidebar__header">
<Avatar
onClick={handleOpen}
src={user.photo}
className="sidebar__avatar"
/>
<div className="sidebar__input">
<SearchIcon />
<input
placeholder="Search"
value={search}
onChange={(e) => searchFunction(e.target.value)}
/>
</div>
<IconButton variant="outlined" className="sidebar__inputButton">
<RateReviewOutlined onClick={addChat} />
</IconButton>
</div>
<div className="sidebar__chats">
{chats.map(({ id, data: { chatName } }) => (
<SidebarChat key={id} id={id} chatName={chatName} />
))}
</div>
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={open}
onClose={handleClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500,
}}
>
<Fade in={open}>
<div className={classes.paper}>
<h2 id="transition-modal-title">
Are you sure you want to sign out?
</h2>
<button onClick={() => auth.signOut()}>Yes</button>
<button onClick={handleClose}>No</button>
</div>
</Fade>
</Modal>
</div>
);
}
You need to save the initial list of chats in a variable and once the search is set to blank '' you need to update your chats with the initial saved chats.
Problem here is -
const filtered = chats.filter(chat => {
return chat.data.chatName.toLowerCase().includes(e.toLowerCase())
});
// console.log(filtered)
setChats(filtered);

Resources