Search bar producing a synthetic event - javascript

I have a search bar component that should take the value of the input, however I am using useState for my getters and setters and i am a bit confused as it is reported an error of
Below is my component, can you spot the erorr?
const SuppliersNavBar = (props) => {
const { classes } = props;
const [search, setSearch] = useState();
const updateSearch = (event) => {
setSearch({ search: event.target.value });
console.log(event);
};
return (
<Fragment><Fab className={classes.addCircle} style={{ float: 'right',
marginRight: 10, marginBottom: 10, backgroundColor: '#3B70BC', color:
'white' }} onClick={() => { this.props.history.push('/'); }}
id="addCircle" ><Add /></Fab>
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<Grid container direction="row"
justify="flex-start"
alignItems="center">
<Grid item xs={12} sm={6} md={3}>
<div className={classes.grow} />
<div className={classes.search} aria-label="search bar">
<div className={classes.searchIcon}>
<Search id="searchIcon" />
</div>
<InputBase
aria-label="search bar"
value={search}
onChange={updateSearch.bind(this)}
placeholder="Search"
classes={{
root: classes.inputRoot,
input: classes.inputInput,
}}
/>
</div>
</Grid>
</Grid>
</Toolbar>
</AppBar>
</div>
</Fragment>
);
};

Events in React are handled through object pooling meaning that events aren't readable through the console. You can call event.persist() and you will be able to see it. Please look at this page for further information. https://reactjs.org/docs/events.html

Related

ReactJS MaterialUI Modal not refreshing

i have a Modal:
with certain fields, if i open the dropdown and select one of the fields, it does change the state of the Object but doesnt render it in the UI (i reopen the dropdown with the selections so you can see whats behind):
the weird thing about it is, if i do it outside of the Modal, it does work, so it has anything todo with my Modal component?
Here is the BaseModal component:
declare interface IBaseModal {
readonly sx: BaseModalStyle;
readonly body?: React.ReactNode;
readonly isOpen: boolean;
readonly toggleModal: any;
}
const BaseModal: FC<IBaseModal> = ({sx, body, isOpen, toggleModal}: IBaseModal) => (
<Modal open={isOpen} onClose={toggleModal}>
<BaseModalView width={sx.width} height={sx.height}>
{body}
</BaseModalView>
</Modal>
)
then i use it as follows in the view component:
<BaseModal
sx={{width: 800, height: 600}}
isOpen={isModalOpen}
toggleModal={() => setModalOpen(isModalOpen)}
body={modalBody}
/>
const localizer = momentLocalizer(moment);
const [events, setEvents] = useState<CalendarEvent[]>([])
const [schedule, setSchedule] = useState<ISchedule>(initialScheduleEvent);
const [isModalOpen, setModalOpen] = useState<boolean>(false);
const [modalBody, setModalBody] = useState<React.ReactNode | undefined>();
const handleSelectDate = (e: SlotInfo) => {
setModalBody(<Grid container>
<Grid item xs={6}>
<Grid container direction="row" sx={{padding: 2}}>
<Grid item xs={12} sx={{marginBottom: 2}}>
<Typography variant="h5" align='center'>
Schedule your Post
</Typography>
</Grid>
<Grid item xs={12} sx={{marginBottom: 2}}>
<Divider/>
</Grid>
<Grid item xs={12} paddingBottom={3}>
<TextField
style={{marginBottom: 20}}
fullWidth
select
variant="outlined"
label="Plattform"
value={schedule.platform}
onChange={e => setSchedule(prevState => ({...prevState, platform: e.target.value}))}
>
{availableSocialMedias.map(item => (
<MenuItem key={item.socialMedia} value={item.socialMedia}>{item.socialMedia}</MenuItem>
))}
</TextField>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DateTimePicker
renderInput={(props) => <TextField {...props} />}
label="Schedule Date and Time"
value={schedule.schedule.start}
onChange={(e) => {
setSchedule(prevState => ({...prevState, schedule: {
...prevState.schedule, start: e!
}}))
}}
/>
</LocalizationProvider>
<TextField
fullWidth
margin="dense"
multiline
rows="5"
variant="outlined"
label="Post Content"
id="additional-info"
value={schedule.schedule.desc}
onChange={(e) => {
setSchedule(prevState => ({...prevState, schedule: {
...prevState.schedule, desc: e.target.value
}}))
}}
/>
</Grid>
<Grid item xs={12} sx={{width: '100%'}}>
<Stack spacing={2} direction="row" justifyContent='center'>
<Button variant='contained' onClick={() => createEvent()}>Post</Button>
<Button variant='contained' onClick={() => handleCloseModal()}>Close</Button>
</Stack>
</Grid>
</Grid>
</Grid>
<Grid item xs={6} sx={{backgroundColor: '#F7706EFF', justifyContent: 'center'}}>
<img style={{height: 250, width: 400}}
src={"https://web-static.wrike.com/blog/content/uploads/2020/01/Five-Features-of-a-Good-Monthly-Employee-Work-Schedule-Template.jpg?av=718acbc1e2b21264368f12b5cc57c0e2"}/>
<img style={{height: 250, width: 400}}
src={"https://imageio.forbes.com/specials-images/imageserve/605e039657de8844e59d9140/Businesswoman-Planning-Schedule-Using-Calendar-And-Laptop/0x0.jpg?format=jpg&crop=922,615,x0,y0,safe&width=960"}/>
<Typography align='center' variant='h6'>
Schedule for the whole week!
</Typography>
</Grid>
</Grid>)
setModalOpen(true);
}
It also rerenders after i select a certain value in the dropdown for example. but the Modal does not update its value, and i dont get why... i hope for any help.
Small Edit:
After selecting a value and closing / reopening the Modal, the value does change, but why not straight after selecting it but after reopening it?
I fixed the issue having the Body of the Modal, not in a variable but straight in the return body of the component

I am passing the state to a function component via history (react-router-dom) but it says the state is 'undefined'

I need to pass the state value to a different component and I want to use it in the different component.
Code in the first component:
const handleFormSubmit = async (event) => {
event.preventDefault()
console.log(formData)
try {
await axios
.post(`http://localhost:4000/accounts/register`, formData)
.then(function (response) {
console.log(response)
console.log(response.data)
setServerMessage(response.data)
})
} catch (error) {
console.log(error)
}
history({
pathname: '/session/verifyotp',
state: { serverMessage: serverMessage.message },
})
}
The second component where I am trying to access the state.
const navigate = useNavigate()
let data = useLocation()
console.log(data)
I have tried to log the current state value in the console using this:
useEffect(() => {
console.log(serverMessage)
}, [serverMessage])
I have tried to set the state in useffect like this:
useEffect(() => {
setServerMessage(serverMessage)
}, [serverMessage])
The output I am getting in the browser console is:
Object { pathname: "/session/verifyotp", search: "", hash: "", state: null, key: "n1jhatdj" }
This is the complete code in the page :
import React, { useEffect, useState } from 'react'
import { Box, styled } from '#mui/system'
import { Grid, Button } from '#mui/material'
import { ValidatorForm, TextValidator } from 'react-material-ui-form-validator'
import Typography from '#mui/material/Typography'
import { FormLabel } from '#mui/material'
import Link from '#mui/material/Link'
import axios from 'axios'
import Appbar from '../Appbar'
import Alert from '#mui/material/Alert'
import Snackbar from '#mui/material/Snackbar'
import { useNavigate } from 'react-router-dom'
const FlexBox = styled(Box)(() => ({
display: 'flex',
alignItems: 'center',
}))
const JustifyBox = styled(FlexBox)(() => ({
justifyContent: 'center',
}))
const IMG = styled('img')(() => ({
width: '100%',
}))
const JWTRegister = styled(JustifyBox)(() => ({
background: '#ffffff',
minHeight: '100vh !important',
input: {
background: 'white',
borderRadius: 25,
},
}))
const JwtRegister = (props) => {
const [serverMessage, setServerMessage] = useState('')
const [open, setOpen] = useState(false)
const history = useNavigate()
const [formData, setFormData] = useState({
name: '',
mobile: '',
email: '',
password: '',
})
const handleClick = () => {
setOpen(true)
}
const handleClose = (event, reason) => {
if (reason === 'clickaway') {
return
}
setOpen(false)
}
const { name, mobile, email, password } = formData
const handleChange = (event) => {
setFormData({
...formData,
[event.target.name]: event.target.value,
})
}
const handleFormSubmit = async (event) => {
event.preventDefault()
console.log(formData)
try {
await axios
.post(`http://localhost:4000/accounts/register`, formData)
.then(function (response) {
console.log(response)
console.log(response.data)
const newValue = response.data
setServerMessage(newValue)
})
} catch (error) {
console.log(error)
}
history({
pathname: '/session/verifyotp',
state: { serverMessage: serverMessage },
})
}
useEffect(() => {
console.log(serverMessage)
setServerMessage(serverMessage)
console.log(serverMessage)
}, [serverMessage])
return (
<JWTRegister>
<Grid container>
<Appbar />
<Grid
pt={0}
pl={10}
pr={10}
item
lg={6}
md={6}
sm={6}
xs={12}
sx={{ height: '100vh', backgroundColor: '#3E8BFF' }}
>
<Typography
component="h1"
variant="h3"
sx={{ textTransform: 'none', color: '#000' }}
>
Sign up
</Typography>
<Typography component="h1" variant="h5">
Register now to get 100 free credits
</Typography>
{serverMessage ? (
<>
<Alert
variant="filled"
autohideduration={6000}
severity="success"
>
{serverMessage.message}
</Alert>
<Snackbar
open={open}
autoHideDuration={3000}
onClose={handleClose}
>
<Alert
onClose={handleClose}
severity="success"
sx={{ width: '100%' }}
>
{serverMessage.message}
</Alert>
</Snackbar>
</>
) : null}
<ValidatorForm id="Register" onSubmit={handleFormSubmit}>
<Grid container spacing={2}>
<Grid
item
lg={6}
md={6}
sm={12}
xs={12}
sx={{ mt: 2 }}
>
<FormLabel sx={{ color: '#000000' }}>
Name
</FormLabel>
<TextValidator
sx={{ mb: 3, width: '100%' }}
size="small"
type="text"
name="name"
value={name}
autoFocus
onChange={handleChange}
validators={['required']}
errorMessages={['Name field is required']}
inputProps={{
style: {
borderRadius: 25,
backgroundColor: 'white',
disableUnderline: true,
},
}}
/>
</Grid>
<Grid
item
lg={6}
md={6}
sm={12}
xs={12}
sx={{ mt: 2 }}
>
<FormLabel sx={{ color: '#000000' }}>
Mobile
</FormLabel>
<TextValidator
sx={{ mb: 3, width: '100%' }}
size="small"
type="text"
name="mobile"
value={mobile}
onChange={handleChange}
validators={['required']}
errorMessages={[
'Mobile Number field is required',
]}
inputProps={{
style: {
borderRadius: 25,
backgroundColor: 'white',
disableUnderline: true,
},
}}
/>
</Grid>
</Grid>
<FormLabel sx={{ color: '#000000' }}>Email</FormLabel>
<TextValidator
sx={{ mb: 3, width: '100%' }}
size="small"
type="email"
name="email"
value={email}
onChange={handleChange}
validators={['required', 'isEmail']}
inputProps={{
style: {
borderRadius: 25,
backgroundColor: 'white',
disableUnderline: true,
},
}}
errorMessages={[
'Email field is required',
'Email is not valid',
]}
/>
<FormLabel sx={{ color: '#000000' }}>
Password
</FormLabel>
<TextValidator
sx={{ mb: '16px', width: '100%' }}
size="small"
name="password"
type="password"
value={password}
onChange={handleChange}
validators={['required']}
errorMessages={['Password field is required']}
inputProps={{
style: {
borderRadius: 25,
disableUnderline: true,
backgroundColor: 'white',
},
}}
/>
<FlexBox pb={2}>
<Button
type="submit"
variant="contained"
sx={{
borderRadius: 25,
textTransform: 'none',
background: '#C7FF80',
color: '#000000',
}}
onClick={handleClick}
>
Verify OTP
</Button>
</FlexBox>
</ValidatorForm>
<Typography
variant="subtitle1"
display="inline"
sx={{
textTransform: 'none',
color: '#000000',
}}
>
Already a member?
<Link
href="/session/signin"
sx={{
textTransform: 'none',
color: '#FFFFFF',
}}
>
Sign in
</Link>
instead.
</Typography>
</Grid>
<Grid
pt={1}
pl={10}
item
lg={6}
md={6}
sm={6}
xs={12}
sx={{ height: '100vh', backgroundColor: '#3E8BFF' }}
>
<Typography pb={3} variant="body">
or sign up with
</Typography>
<Grid
pb={3}
pt={3}
container
alignItems="center"
spacing={2}
>
<Grid item>
<IMG
src="/assets/images/signup-linkedin.svg"
height={55}
width={55}
/>
</Grid>
<Grid item>
<Typography pb={1} component="h6" variant="h6">
Linkedin
</Typography>
</Grid>
</Grid>
<Grid pb={3} container alignItems="center" spacing={2}>
<Grid item>
<IMG
src="/assets/images/signup-google.svg"
height={55}
width={55}
/>
</Grid>
<Grid item>
<Typography pb={1} component="h6" variant="h6">
Google
</Typography>
</Grid>
</Grid>
<Grid pb={3} container alignItems="center" spacing={2}>
<Grid item>
<IMG
src="/assets/images/signup-facebook.svg"
height={55}
width={55}
/>
</Grid>
<Grid item>
<Typography pb={1} component="h6" variant="h6">
Facebook
</Typography>
</Grid>
</Grid>
<Grid pb={3} container alignItems="center" spacing={2}>
<Grid item>
<IMG
src="/assets/images/signup-email.svg"
height={55}
width={55}
/>
</Grid>
<Grid item>
<Typography component="h6" variant="h6">
Corporate Email ID
</Typography>
<span pb={1} component="h6" variant="h6">
(Use only Business email)
</span>
</Grid>
</Grid>
</Grid>
</Grid>
</JWTRegister>
)
}
export default JwtRegister
No matter what I try I am not able to pass the state to the different component. I have followed this question but does not solve my problem.
How can I access the state value? Why is it coming as null?
I have found the answer to this question. react-router v6 In You need to use your history like this for react-router v6.
This is not the right way to pass state:
history({
pathname: '/session/verifyotp',
state: { serverMessage: serverMessage.message },
})
Correct way to pass state in react-router v6 is the following:
history("/session/verifyotp", {
state: { serverMessage: serverMessage },
});

I have a component. But the onClick function isn't running

I have a component which i have imported into another component. When I click the component, the onclick function refuses to run.
This is the code for the component
const HomeFeedCard = ({ name, image, published, quantity, weight }) => {
const classes = useHomeFeedCardStyles()
return (
<Grid item xs={6} md={3} sm={4} lg={3}>
<Paper elevation={5}>
<img src={image?.url} alt='Product' className={classes.image} />
<div className={classes.container}>
<Avatar
alt='image'
src='https//user.png'
sx={{ width: 56, height: 56, mr: 1 }}
/>
<div className={classes.textContainer}>
<Typography variant='h6' component='body'>
<LinesEllipsis text={` ${name}`} />
</Typography>
<Typography>{`${quantity} left | ${weight}KG`}</Typography>
</div>
</div>
</Paper>
</Grid>
)
}
THIS IS THE function that runs the onClick function. The console returns nothing
<HomeFeedCard
key={product._id}
name={product.productName}
published={product.published}
image={product.images[0]}
quantity={product.quantity}
weight={product.weight}
onClick={() => console.log('product', product.productName)}
/>
Your onClick is not defined in your function HomeFeedCard.
const HomeFeedCard = ({ name, image, published, quantity, weight, onClick }) => {
return (
<div onClick={onClick} />
)
}
If you don't know which properties you want to set use: https://reactjs.org/docs/jsx-in-depth.html#spread-attributes
In the HomeFeedCard, you are not expecting an onClick function as a prop.
You need to explicitly bind the onClick to an actual element. You can wrap content inside HomeFeedCardwith adiv`.
OR, pass onClick further to Grid if accepts a click handler.
const HomeFeedCard = ({
name,
image,
published,
quantity,
weight,
onClick
}) => {
const classes = useHomeFeedCardStyles();
return (
<div onClick={onClick}>
<Grid item xs={6} md={3} sm={4} lg={3}>
<Paper elevation={5}>
<img src={image?.url} alt="Product" className={classes.image} />
<div className={classes.container}>
<Avatar
alt="image"
src="https//user.png"
sx={{ width: 56, height: 56, mr: 1 }}
/>
<div className={classes.textContainer}>
<Typography variant="h6" component="body">
<LinesEllipsis text={` ${name}`} />
</Typography>
<Typography>{`${quantity} left | ${weight}KG`}</Typography>
</div>
</div>
</Paper>
</Grid>
</div>
);
};
<HomeFeedCard
key={product._id}
name={product.productName}
published={product.published}
image={product.images[0]}
quantity={product.quantity}
weight={product.weight}
onClick={() => console.log("product", product.productName)}
/>

Form is not submitting in react js

I have a form that should print the data in console but unfortunately I'm not able to.
I want to print data to the console when a form is submitted.
The form is not submitting don't know why. I have the code below.
I would be very grateful if you could decide.
import { Button, Grid, Paper, TextField } from "#mui/material";
import React from "react";
import { useForm } from "react-hook-form";
export default function Page2(props) {
const { handleSubmit } = useForm();
const handelInputChange = (e) => {
const { name, value } = e.target;
console.log(name, value);
};
const handleData = (data) => {
console.log("data");
};
return (
<>
<Paper
style={{ margin: "10px auto", textAlign: "center" }}
elevation={24} >
<h1 style={{ textAlign: "center" }}>Todo Application</h1>
<form onSubmit={handleSubmit(handleData)}>
<Grid
style={{ margin: "10px" }}
container
spacing={1}
direction="column" >
<Grid item xs={6}>
<TextField
name="title"
label="Title"
variant="standard"
onChange={handelInputChange} />
<TextField
name="desc"
label="Description"
variant="standard"
onChange={handelInputChange} />
<TextField
name="priority"
type="number"
label="Priority"
variant="standard"
onChange={handelInputChange} />
</Grid>
</Grid>
</form>
<button type="submit" variant="contained" color="primary">
Add
</button>
</Paper>
</>
);
}
You have wrong HTML structure. button[type=submit] should be inside <form> tag
In addition to Steve, You can use simply register function to do the work for you just supply register function in the inputRef of your MUI Form Component.
import { Button, Grid, Paper, TextField } from "#mui/material";
import React from "react";
import { useForm } from "react-hook-form";
export default function Page2(props) {
const { handleSubmit, register } = useForm();
const handelInputChange = (e) => {
const { name, value } = e.target;
console.log(name, value);
};
const handleData = (data) => {
console.log("data",data);
};
return (
<>
<Paper
style={{ margin: "10px auto", textAlign: "center" }}
elevation={24} >
<h1 style={{ textAlign: "center" }}>Todo Application</h1>
<form onSubmit={handleSubmit(handleData)}>
<Grid
style={{ margin: "10px" }}
container
spacing={1}
direction="column" >
<Grid item xs={6}>
<TextField
name="title"
label="Title"
variant="standard"
inputRef={register}
onChange={handelInputChange} />
<TextField
name="desc"
label="Description"
variant="standard"
inputRef={register}
onChange={handelInputChange} />
<TextField
name="priority"
type="number"
label="Priority"
variant="standard"
inputRef={register}
onChange={handelInputChange} />
</Grid>
</Grid>
<button type="submit" variant="contained" color="primary">
Add
</button>
</form>
</Paper>
</>
);
}
You have quite a bit of things to do in order to get this form to console.log. First, as the other poster mentioned, the submit button needs to be within the form (and you probably want to uppercase that B in "<Button" so that you're using the MUI component.
<form onSubmit={handleSubmit(handleData)}>
<Grid
style={{ margin: "10px" }}
container
spacing={1}
direction="column"
>
<Grid item xs={6}>
<TextField
name="title"
label="Title"
variant="standard"
onChange={handelInputChange}
/>
...
</Grid>
</Grid>
// Moved and renamed here
<Button type="submit" variant="contained" color="primary">
Add
</Button>
</form>
That solves your submit problem, but then you will notice that the console.log("data") will only ever contain an empty object {} -- this is because react-form-hooks needs to be given a FormProvider and made aware of the form elements in the form that it should control. To do this you need to register the component. I have added working code example on one way to complete this task.
In this example, I created a generic FormFieldController wrapper that you can use to pass in whatever just about form fields you need. (I would not use this in production code, without cleanup, as it is only meant as an example):
const FormFieldController = ({
component: Component = TextField,
name = "",
defaultValue = "",
label = "",
validation = {},
required = false,
valueProp = "value",
callbackProp = "onChange",
onChange,
...rest
}) => {
const { control } = useFormContext();
return (
<Controller
name={name}
control={control}
defaultValue={defaultValue}
rules={validation}
render={({
field: { onChange: internalOnChange, value, ref },
fieldState: { error }
}) => {
const pipes = {
[valueProp]: value,
[callbackProp]: function () {
internalOnChange.apply(this, arguments);
// Middleman callback to allow for onChange back to the caller, if needed
if (onChange) {
onChange.apply(this, arguments);
}
}
};
return (
<>
<Component
id={name}
inputRef={ref}
caption={error ? error?.message : ""}
label={label}
{...pipes}
{...rest}
/>
</>
);
}}
/>
);
};
Working CodeSandbox Example

Getting undefined values while using UseContext in React

Context that I created to use useState across my component:
context.js:
const searchContext = React.createContext();
This is where I created a useState with searchText with initial state as an empty string.
Header.js:
import { useState } from "react";
import { searchContext } from "./context";
import { useSelector } from 'react-redux';
import Motherboard from "./Components/Motherboard";
function Header() {
const[searchText,setSearchText] = useState("");
const cart = useSelector(state => state.cart);
return (
<div
style={{ backgroundColor: "#191C27", paddingLeft: 0, paddingRight: 0 }}
>
<Navbar
variant="light"
expand="lg"
style={{ backgroundColor: "#191C27" }}
>
<Container>
<Navbar.Toggle aria-controls="navbarScroll">
<img src={options} alt="options" width="30px" />
</Navbar.Toggle>
<Navbar.Brand className="mr-auto" href="#">
<Link to='home'>
<img
className="logoIcon"
src={logo}
alt="logo"
style={{ width: 130 }}
/>
</Link>
</Navbar.Brand>
<Navbar.Collapse id="navbarScroll">
<Nav
className="ml-auto my-2 my-lg-0"
style={{ maxHeight: "100px", marginRight: "5%" }}
navbarScroll
>
<Nav.Link>
<Link to='/motherboard' className="links">
Motherboard
</Link>
</Nav.Link>
<Nav.Link onClick={(e) => e.preventDefault()}>
<Link to='/processor' className="links">
Processor
</Link>
</Nav.Link>
<Nav.Link>
<Link to='/ram' className="links">
RAM
</Link>
</Nav.Link>
<Nav.Link>
<Link to='/hdd' className="links">
HDD
</Link>
</Nav.Link>
<Nav.Link>
<Link to='/graphic' className="links">
Cabinet
</Link>
</Nav.Link>
</Nav>
</Navbar.Collapse>
<Form className="d-flex" style={{ marginRight: "2%" }}>
<searchContext.Provider value={searchText}>
<Motherboard></Motherboard>
</searchContext.Provider>
<FormControl
type="search"
placeholder="Search"
onChange={event => {setSearchText(event.target.value)}}
className="mr-2"
aria-label="Search"
style={{background:'transparent', borderRadius:0, color:'white'}}
/>
</Form>
Now I tried using my useContext and called the useState value searchText here in Motherboard component. But getting some undefined errors while running.
Motherboard.js:
import {searchContext} from '../context'
const dummy = Array.from(Array(10));
function Motherboard(props) {
let context = useContext(searchContext);
const [loading, setLoading] = React.useState(true);
// const [products, setProducts] = React.useState([]);
const products = useSelector((state) => state.products);
const dispatch = useDispatch();
useEffect(() => {
axios
.post("/product?limit=50&page=1&category=motherboard")
.then((res) => {
console.log(res, "res");
dispatch({
type: actionTypes.GET_PRODUCTS,
payload: res.data.products,
});
setLoading(false);
})
.catch((err) => {
setLoading(false);
console.log(err);
});
}, []);
const styleCol = {
backgroundColor: "#0F0F13",
};
if (loading) {
return (
<div className='loadDiv'>
<ClipLoader size="150" color="white" style={{marginTop: -200}}/>
</div>
);
}
return (
<div className="filterDiv">
<Banner />
<Container fluid="md">
<Row>
<Col lg={3} style={styleCol} className="colFilter">
<div>
<div style={{ backgroundColor: "#191C27" }}>
<Accordion>
<AccordionSummary
aria-controls="panel1a-content"
id="panel1a-header"
>
<Typography>SORT BY PRICE</Typography>
</AccordionSummary>
<div className="filterDiv">
<AccordionDetails>
<FormControl component="fieldset">
<RadioGroup aria-label="gender" name="gender1">
<FormControlLabel
value="hightolow"
control={<Radio />}
label="Highest to Lowest"
className="radioBtn"
/>
<FormControlLabel
value="lowtohigh"
control={<Radio />}
label="Lowest to Highest"
className="radioBtn"
/>
</RadioGroup>
</FormControl>
</AccordionDetails>
</div>
</Accordion>
</div>
<div style={{ backgroundColor: "#191C27" }}>
<Accordion>
<AccordionSummary
aria-controls="panel1a-content"
id="panel1a-header"
>
<Typography className="heading">SUB CATEGORY</Typography>
</AccordionSummary>
<div className="filterDiv">
<AccordionDetails>
<FormControl component="fieldset">
<RadioGroup aria-label="processor" name="prcocessor">
<FormControlLabel
value="hightolow"
control={<Radio />}
label="INTEL"
className="radioBtn"
/>
<FormControlLabel
value="lowtohigh"
control={<Radio />}
label="AMD"
className="radioBtn"
/>
</RadioGroup>
</FormControl>
</AccordionDetails>
</div>
</Accordion>
</div>
</div>
</Col>
<Col
xs={12}
lg={9}
sm={12}
md={12}
style={{ backgroundColor: "#0F0F13", paddingTop: 27 }}
>
<Row>
{products.filter((product) => {
if(context.searchText == '') {
return product
}
else if(product.productName.toLowerCase.includes(context.searchText.toLowerCase())){
return product
}}).map((product, index) => {
return (
<Col key={index} lg={4} md={6} xs={12} sm={6}>
<div
you can try to define value as object. the error is probably due to the value not being an object
<searchContext.Provider value={{ searchText }}>
<Motherboard></Motherboard>
</searchContext.Provider>
As you wrote context.searchText, you have to store an object inside the value of the provider:
<searchContext.Provider value={{ searchText }}>
<Motherboard />
</searchContext.Provider>
use context instead of context.searchText in MotherBoard.js because you are passing a string as the value in the provider so when call the context using useContext , it gives the latest value of the provider which is what you typed in the search box.

Categories

Resources