How to get the field values in react material ui components - javascript

This works but the when i console log the object it gives
{ "week":undefined, "name":undefined, "code":undefined }
Moreover does wrapping all the material ui component in form tag and treating the whole code as a form, is it appropriate?
here is my code:
const ExamSimulatorForm = () => {
const weekNumber = useRef();
const examSub = useRef();
const examCode = useRef();
const handleSubmit = (event) =>{
event.preventDefault()
const week = weekNumber.current.value
const subject = examSub.current.value
const code = examCode.current.value
const examSimulatorPayload = {
week:week,
subject:subject,
code:code
}
console.log(examSimulatorPayload)
}
const [code, setCode] = useState('Quiz');
const [examSubject, setExamSubject] = useState('');
const [field, setField] = useState(1)
const handleESubjectChange = (event) => {
setExamSubject(event.target.value);
};
const handleCode = (event) => {
setCode(event.target.value);
};
return (
<form >
<CardActions onSubmit={handleSubmit}>
<Grid container spacing={2} justifyContent='center' alignItems='center' direction='column'>
<Grid item>
<TextField
InputProps={{
inputProps: {
max: 12, min: 1
}
}}
label='Week'
type='number'
onChange={(event)=>setField(parseInt(event.target.value))}
style={{minWidth:250}}
ref = {weekNumber}
required
/>
</Grid>
<Grid item>
<FormControl style={{minWidth:250}}>
<InputLabel>Subject</InputLabel>
<Select
value={examSubject}
onChange={handleESubjectChange}
ref={examSub}
required
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item>
<FormControl style={{minWidth:250}}>
<InputLabel id="exam-code" >Exam Code</InputLabel>
<Select
labelId="exam-code"
id="exam-code-select"
value={code}
onChange={handleCode}
ref={examCode}
required
>
<MenuItem value={'Q'}>Q</MenuItem>
<MenuItem value={'M'}>M</MenuItem>
<MenuItem value={'F'}>F</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item>
<Button variant='contained' color='primary' style={{marginTop:94}} >Take Exam</Button>
</Grid>
</Grid>
</CardActions>
</form>
)
}
export default ExamSimulatorForm;
I have a similar form for attendance simulation, attendance dataset generation and exam dataset generation

I think this is good for you.
Please try this.
const ExamSimulatorForm = () => {
const [state, setState] = useState({
code: 'Quiz',
subject: '',
week: 1
});
const handleSubmit = (event) =>{
event.preventDefault()
const examSimulatorPayload = state;
console.log(examSimulatorPayload)
}
const handleChange = (evt, name) {
const { value } = evt.target;
setState({
...state,
[name]: value
});
}
return (
<form onSubmit={handleSubmit}>
<CardActions>
<Grid container spacing={2} justifyContent='center'
alignItems='center' direction='column'>
<Grid item>
<TextField
InputProps={{
inputProps: {
max: 12, min: 1
}
}}
label='Week'
type='number'
value={state.week}
onChange={(event)=>handleChange( event, "week")}
style={{minWidth:250}}
required
/>
</Grid>
<Grid item>
<FormControl style={{minWidth:250}}>
<InputLabel>Subject</InputLabel>
<Select
value={state.subject}
onChange={(event)=>handleChange( event, "subject")}
required
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item>
<FormControl style={{minWidth:250}}>
<InputLabel id="exam-code" >Exam Code</InputLabel>
<Select
labelId="exam-code"
id="exam-code-select"
value={state.code}
onChange={(event)=>handleChange( event, "code")}
required
>
<MenuItem value={'Q'}>Q</MenuItem>
<MenuItem value={'M'}>M</MenuItem>
<MenuItem value={'F'}>F</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item>
<Button variant='contained' color='primary' style=
{{marginTop:94}} >Take Exam</Button>
</Grid>
</Grid>
</CardActions>
</form>
)
}
export default ExamSimulatorForm;
Please check it above code, and let me know your idea.

State updates in react are asynchronus, which means they don't occur as soon as you call them. You have to wait until the state updates to console.log because otherwise, nothing has changed and you are getting the initial value. You could do something like this:
useEffect(() => {
const subject = examSub.current.value
console.log(subject)
}, [examSubject])
useEffect() executes an action every time a state changes. Notice how at the end there is an array, with [examSubject]. This signifies the state that will trigger the effect. So when examSubject changes (when you assign a value to it), the effect will execute (in this case, it will log the subject).
When writing code, at least in my case, you don't need to worry about this. You can chnage the state and write your code as normal, but react might take a second or two to update the state. The only time I really notice this is when I console.log.

You can define the state for your inputs :
const [code, setCode] = React.useState('');
const [subject, setSubject] = React.useState('');
const [week, setWeek] = React.useState('');
const setExamCode = event => {
setCode(event.target.value);
};
const setSubject = event => {
setSubject(event.target.value);
};
const setWeek = event => {
setWeek(event.target.value);
};
Then call these methods from onChange event like : onChange={setExamCode} or {setSubject}
In case you want to handle data from single event and defining it's initial state try below approach :
const initialData = Object.freeze({
code: "",
subject: "",
week: ""
});
const [data, updateData] = React.useState(initialData );
const handleChange = (e) => {
updateData({
...data,
[e.target.name]: e.target.value
});
};
const handleSubmit = (e) => {
e.preventDefault()
console.log(data);
};
Then call these methods from onChange event like onChange={handleSubmit}

Related

I use useState hock to store the value but it did not update

I am new to Reactjs
I am trying to build an address form with 3 Select ( country, State, City )
I used React hock
so when the page first load it will fetch countries list to country select after that when user select country it will fetch states list to state select and after that when user select state it will fetch cities list to city select
my issue with state hock I store the value of the user selected in the state but it did not update the value in the state in many locations I keep getting " undefined " like when the page load I get countries list as an array and I get the first country in the list as the default select item in country select but I still get keep getting " undefined " I tried many ways but still getting the same result and bellow is my code
import React,{ useEffect , useState , useCallback } from 'react';
import { InputLabel, Select , MenuItem , Grid , Typography } from '#material-ui/core';
import { useForm, FormProvider } from 'react-hook-form';
import CityHandler from 'countrycitystatejson';
export const TempAddresForm = () =>
{
const methods = useForm();
const [countries, setCountries] = useState([]);
const [countryCode, setCountryCode] = useState('');
const [country, setCountry] = useState('');
const [states, setStates] = useState([]);
const [stateName, setStateName] = useState('');
const [cities, setCities] = useState([]);
const [city, setCity] = useState('');
const fetchCounters = () => {
setCountries(CityHandler.getCountries());
setFirstCountry();
};
const countryChangeHandler = (event) => {
let tempCountryCode = event.target.value;
setCountry(CityHandler.getCountryByShort(tempCountryCode));
setCountryCode(tempCountryCode);
fetchStates(tempCountryCode);
setCities([]);
}
const fetchStates = (countryCode) =>
{
setStates(CityHandler.getStatesByShort(countryCode));
}
const stateChangeHandler = (even) =>
{
let tempState = even.target.value;
setStateName(even.target.value);
fetchCities(tempState);
}
const fetchCities = (stateName) => {
let tempCities = CityHandler.getCities(countryCode, stateName);
setCities(tempCities);
};
const cityChangeHandler = (event) =>
{
let tempCity = event.target.value;
setCity(tempCity);
console.log("Temp City Name : " + tempCity)
console.log("City Name : " + city)
}
const setFirstCountry = useCallback( () =>
{
if(countries)
{
let firstCountry = CityHandler.getCountries()[0];
console.log ("[setFirstCountry] : First Country " + JSON.stringify(firstCountry.name));
setCountry(firstCountry);
console.log ("[setFirstCountry] : Country name " + JSON.stringify(country.name));
}
}, []);
useEffect(() => {
fetchCounters();
//setFirstCountry();
}, []);
return (
<>
<Typography variant="h6" gutterBottom>Shipping Address</Typography>
<FormProvider {...methods}>
<form onSubmit={''}>
<Grid container spacing={3}>
<Grid item xs={12} sm={6}>
<InputLabel>Country</InputLabel>
<Select value={country.name} fullWidth onChange={(event) => {countryChangeHandler(event)}}>
{countries.map((countryLoop) => (
<MenuItem key={countryLoop.shortName} id={countryLoop.shortName} value={countryLoop.shortName}>
{countryLoop.name}
</MenuItem>
))}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>State</InputLabel>
<Select value={stateName} fullWidth onChange={(event) => {stateChangeHandler(event)}}>
{states.map((state, index) => {
return(
<MenuItem key={index} id={state} value={state}>
{state}
</MenuItem>
);
})}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>City</InputLabel>
<Select value={city} fullWidth onChange={(event) => {cityChangeHandler(event)}}>
{cities.map((city, index) => {
return(
<MenuItem key={index} id={city} value={city}>
{city}
</MenuItem>
);
})}
</Select>
</Grid>
</Grid>
</form>
</FormProvider>
</>
)
}
export default TempAddresForm;
if anyone could help me with this
*Note: I use this package to get the Country list countrycitystatejson
country is actually always updating but you are logging it in a useCallback hook and did not add country to its dependency array. So it only captures the initial value of country which is an empty string "" and JSON.stringify("".name) is undefined. If you add country to the dependency array of useCallback you will see it updating.
console.log( JSON.stringify("".name) )
You don't need to use useCallback here. Read this article to understand where and when to use useCallback and useMemo
The main problem is that you are mapping your country Select to country.name but your select options have country.shortName as their value - Try changing the Select value to country.shortName.
Also, you have too many state variables that are interdependent to each other. Here moving all your state variables to a single state object will make it a little bit easier to handle.
Ex Like below
{
countries: [...],
states: [...],
cities: [...],
stateName: "..",
...
...
}
countries is always constant & states, cities are just derived values. So your actual state just needs these 3 values countryShortCode, stateName and city.
Here is a snippet with all the above-mentioned changes
import React, { useState } from "react";
import {
InputLabel,
Select,
MenuItem,
Grid,
Typography
} from "#material-ui/core";
import { useForm, FormProvider } from "react-hook-form";
import CityHandler from "countrycitystatejson";
// This countriesList doesn't change so it can just be a constant outside your component
const countriesList = CityHandler.getCountries();
// Your initial state
const initialState = {
countryShortName: countriesList[0].shortName,
stateName: "",
city: ""
};
const TempAddresForm = () => {
const methods = useForm();
const [state, setState] = useState(initialState);
const changeCountry = (e) => {
setState((prevState) => ({
...prevState,
countryShortName: e.target.value,
stateName: "",
city: ""
}));
};
const changeState = (e) => {
setState((prevState) => ({
...prevState,
stateName: e.target.value,
city: ""
}));
};
const changeCity = (e) => {
setState((prevState) => ({
...prevState,
city: e.target.value
}));
};
// Derive both states and cities here ( No need to store it in state :) )
const states = CityHandler.getStatesByShort(state.countryShortName);
const cities = state.stateName
? CityHandler.getCities(state.countryShortName, state.stateName)
: [];
return (
<>
<Typography variant="h6" gutterBottom>
Shipping Address
</Typography>
<FormProvider {...methods}>
<form onSubmit={() => console.log("Submitted")}>
<Grid container spacing={3}>
<Grid item xs={12} sm={6}>
<InputLabel>Country</InputLabel>
<Select
value={state.countryShortName || ""}
fullWidth
onChange={changeCountry}
>
{countriesList.map((countryLoop) => (
<MenuItem
key={countryLoop.shortName}
id={countryLoop.shortName}
value={countryLoop.shortName}
>
{countryLoop.name}
</MenuItem>
))}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>State</InputLabel>
<Select value={state.stateName} fullWidth onChange={changeState}>
{states.map((state, index) => {
return (
<MenuItem key={index} id={state} value={state}>
{state}
</MenuItem>
);
})}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>City</InputLabel>
<Select value={state.city || ""} fullWidth onChange={changeCity}>
{cities.map((city, index) => {
return (
<MenuItem key={index} id={city} value={city}>
{city}
</MenuItem>
);
})}
</Select>
</Grid>
</Grid>
</form>
</FormProvider>
</>
);
};
export default TempAddresForm;
Comment if you need to understand anything else

Material-UI TextField loses focus on every onChange

I am creating the following component:
It will contain an array of objects, where each object is a prescription, with the medicine name from the select and a TextField for the Dosis.
My problem is that the TextField loses focus on every onChange() and is very frustrating because it cannot be edited on a single focus.
This is my component :
const MedicineSelect = ({ medications, setMedications, ...props }) => {
const { medicines } = useMedicines()
const classes = useStyles()
const handleChange = (index, target) => {
// setAge(event.target.value)
const newMedications = cloneDeep(medications)
newMedications[index][target.name] = target.value
setMedications(newMedications)
}
const handleAddMedicine = () => {
const newMedications = cloneDeep(medications)
newMedications.push({ medicine: '', dosis: '', time: '' })
setMedications(newMedications)
}
const handleDeleteMedicine = (index) => {
console.log('DELETE: ', index)
const newMedications = cloneDeep(medications)
newMedications.splice(index, 1)
setMedications(newMedications)
}
return (
<Paper style={{ padding: 5 }}>
<List>
{medications.map((medication, index) => (
<ListItem key={nanoid()} divider alignItems='center'>
<ListItemIcon>
<Tooltip title='Eliminar'>
<IconButton
className={classes.iconButton}
onClick={() => handleDeleteMedicine(index)}
>
<HighlightOffOutlinedIcon />
</IconButton>
</Tooltip>
</ListItemIcon>
<FormControl className={classes.formControl}>
<InputLabel
id={`${index}-select-${medication}-label`}
>
Medicamento
</InputLabel>
<Select
labelId={`${index}-select-${medication}-label`}
id={`${index}-select-${medication}`}
name='medicine'
value={medication.medicine}
onChange={(event) =>
handleChange(index, event.target)
}
>
{medicines.map((medicine) => (
<MenuItem
key={nanoid()}
value={medicine.name}
>
{medicine.name}
</MenuItem>
))}
</Select>
</FormControl>
<TextField
// fullWidth
id={`${index}-text-${medication}`}
label='Dosis'
name='dosis'
onChange={(event) =>
handleChange(index, event.target)
}
value={medication.dosis}
/>
</ListItem>
))}
<Button onClick={handleAddMedicine}>+ agregar</Button>
</List>
</Paper>
)
}
And here is where I set the component:
const [medications, setMedications] = useState([
{ medicine: '', dosis: '', time: '' },
])
...
<Grid item md={12} xs={12}>
<Accordion>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls='panel1a-content'
id='panel1a-header'
>
<Typography variant='h4'>
Tratamiento:
</Typography>
</AccordionSummary>
<AccordionDetails>
<Container disableGutters>
<MedicineSelect
medications={medications}
setMedications={setMedications}
/>
</Container>
</AccordionDetails>
</Accordion>
</Grid>
...
Adding and removing objects from the array works perfect. selecting the medicine from the select, also works perfect. the only problem I have is when editing the Dosis TextField, with every character, the focus is lost and I have to click again on the TextField.
Please help me getting this fixed!!!
After searching a lot, finally I found the solution. Actually when using nanoid() to create unique keys, on every state update React re-renders all components and since the id of both the List and the TextField component are regenerated by nanoid on every render, React loses track of the original values, that is why Focus was lost.
What I did was keeping the keys unmuttable:
<ListItem key={`medication-${index}`} divider alignItems='center'>
and
<TextField
key={`dosis-${index}`}
fullWidth
// id={`${index}-dosis-${medication}`}
label='Dosis'
name='dosis'
onChange={(event) =>
handleChange(index, event.target)
}
value={medication.dosis}
/>

Checkbox value is not passed properly to the backend API

I have a registration page created in ReactJS. One of the fields is a checkbox isadult. When I click on Register button and save the fields in a database (MongoDB), the value of isadult appears as [Object object] instead of a concrete value: True or False.
What am I doing wrong?
import React from 'react';
import { Paper, makeStyles, Grid, TextField, Button, Switch } from '#material-ui/core';
import config from '../../config/config.json';
import axios from 'axios';
const useStyles = makeStyles((theme) => ({
root: {
minWidth: '300px',
width: '50%',
padding: '20px 20px 20px 20px',
margin: 'auto'
}
}));
const Register = () => {
const classes = useStyles();
const [username, setUsername] = React.useState('');
const [password, setPassword] = React.useState('');
const [isadult, setIsAdult] = React.useState('');
const handleChangeIsAdult = (event) => {
setIsAdult({
...isadult,
[event.target.name]: event.target.value,
});
}
const handleRegister = () => {
if (username && password) {
const formData = new FormData();
formData.append('username', username);
formData.append('password', password);
formData.append('isadult', isadult);
axios.post(config.api.url + '/auth/register', formData)
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
}
}
return (
<Paper className={classes.root}>
<div >
<Grid container spacing={8} alignItems="flex-end">
<Grid item md={true} sm={true} xs={true}>
<TextField
id="username"
label="Username"
type="email"
fullWidth
value={username}
onChange={(e) => setUsername(e.target.value)}
autoFocus />
</Grid>
</Grid>
<Grid container spacing={8} alignItems="flex-end">
<Grid item md={true} sm={true} xs={true}>
<TextField
id="password"
label="Password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
fullWidth />
</Grid>
</Grid>
<Grid container spacing={8} alignItems="flex-end">
<Grid item md={true} sm={true} xs={true}>
<label>Is adult?</label>
<input
type='checkbox'
onChange={(event) => {
handleChangeIsAdult({
target: {
name: event.target.name,
value: event.target.checked,
},
});
}}
/>
</Grid>
</Grid>
<Grid container justify="center" style={{ marginTop: '10px' }}>
<Button
variant="outlined"
color="primary"
style={{ textTransform: "none" }}
onClick={handleRegister}
>
Register
</Button>
</Grid>
</div>
</Paper>
);
}
export default Register;
As your isadult state property is intended for use in the checkbox input, it needs to be declared and updated as a boolean.
You are declaring the propery as follows:
const [isadult, setIsAdult] = React.useState('');
The initial assignment is the empty string (''), which may cause issues with other places in your application code if they expect that property to be of type boolean. What you should do instead is start it off as a boolean:
const [isadult, setIsAdult] = React.useState(false);
Now, the main problem you are facing is the fact that the form data is being serialized with isadult being an object. This problem is coming from the fact that you are assigning an object to it through setIsAdult:
setIsAdult({
...isadult,
[event.target.name]: event.target.value,
});
The state property setter appends whatever value is passed to it directly to the property it is attached to. It works differently from setState that expects a state object. The right way to use the method in this case is:
setIsAdult(event.target.value);
Here, event.target.value contains exactly the checkbox checked boolean value that should go into isadult. Now, this property is serialized correctly as a boolean in your formData.

React hook console.log and interface

Before I ask my question: Yes I did read every other article about this but im basicly just stuck and can't figure out how to fix this.
So basically my rendering and console.log are one step behind my useState changes. The biggest problem visually and functionally is the dynamic button which doesn't enable/disable correctly. My code is:
import React, { useState, useEffect } from 'react';
import ApiCalls from "../../classes/apiCallsClass"
import useStyles from "./styles";
import { TextField, Select, Paper, Grid, MenuItem, Button } from '#material-ui/core';
import { withStyles } from "#material-ui/styles";
export default function TicketCreation() {
const [buttonDisabled, setButtonDisabled] = useState(true);
const [, setTick] = useState(0);
const classes = useStyles();
const [ticketname, setTicketName] = useState('');
const [description, setDescription] = useState('');
const [prio, setPrio] = useState('');
const [system, setSystem] = useState('');
const handleChangePrio = event => {
setPrio(event.target.value);
checkFormFilled();
};
const handleChangeDescription = event => {
setDescription(event.target.value);
checkFormFilled();
};
const handleChangeName = event => {
setTicketName(event.target.value);
checkFormFilled();
};
const handleChangeSystem = event => {
setSystem(event.target.value);
checkFormFilled();
};
const checkFormFilled = () => {
if (ticketname && description && prio && system) {
setButtonDisabled(false, function(){
setTick(tick => tick + 1);
});
} else{
setButtonDisabled(true, function(){
setTick(tick => tick + 1);
});
}
}
const handelButtonSubmit = event => {
if (ApiCalls.createTicket(ticketname, system, prio, description)) {
console.log("Created");
}
}
return (
<div className={classes.root}>
<Grid container spacing={3}>
<Grid item xs={4}>
<Paper className={classes.paper}>
<TextField id="standard-basic" value={ticketname} onChange={handleChangeName} label="Ticketname" fullWidth />
</Paper>
</Grid>
<Grid item xs={4}>
<Paper className={classes.paper}>
<Select value={system} onChange={handleChangeSystem} displayEmpty fullWidth className={classes.selectEmpty}>
<MenuItem value="" disabled>
System
</MenuItem>
<MenuItem value={1}>Radar</MenuItem>
<MenuItem value={2}>Missles</MenuItem>
<MenuItem value={3}>Toilet</MenuItem>
</Select>
</Paper>
</Grid>
<Grid item xs={4}>
<Paper className={classes.paper}>
<Select value={prio} onChange={handleChangePrio} displayEmpty fullWidth className={classes.selectEmpty}>
<MenuItem value="" disabled>
Priority
</MenuItem>
<MenuItem value={1}>Low</MenuItem>
<MenuItem value={2}>Medium</MenuItem>
<MenuItem value={3}>High</MenuItem>
</Select>
</Paper>
</Grid>
<Grid item xs={12}>
<Paper className={classes.paper}>
<TextField
value={description}
onChange={handleChangeDescription}
id="outlined-multiline-static"
label="Ticket description"
multiline
rows="4"
variant="outlined"
fullWidth />
</Paper>
</Grid>
<Grid item xs={12}>
<Button disabled={buttonDisabled} onClick={handelButtonSubmit} variant="contained" color="primary">
Create
</Button>
</Grid>
</Grid>
</div>
);
}
Don't mind the setTick usestate, I tried this in combination with a callback to fix the issue but it wasn't working.
My question basically is:
What do I need to do to enable my button instantly without delay? (and maybe other things I do wrong? first time using react hooks)
State setters (setSystem, etc.) are asynchronous. That means where you're doing things like setSystem(event.target.value); checkFormFilled() -- the new value of system, in this case, may not be updated by the time checkFormFilled runs. That's likely why you're seeing things "lag behind" the values.
What you should be doing is not calling checkFormFilled directly after your set state calls; instead, put checkFormFilled in a useEffect hook that depends on the form elements. That way, React will call your checkFormFilled function when any of those values are actually updated.
useEffect(() => {
checkFormFilled();
}, [ticketname, description, prio, system]);
Then your change handlers only need to worry about setting the values, not calling the form filled check, and everything is guaranteed to be up to date.

Remove asterisk from only one field

I have a custom component that takes in values from an API and then displays them to a user, however within this component I give a 'required' flag to give an asterisk to the label, however I only want one field as seen below to have an asterisk not both as is currently happening.
<Grid item xs={12} sm={6}>
<SearchUsers
name="primaryOfficerId"
label="PO Responsible"
id="primaryOfficerId"
onSelect={change.bind(null, 'primaryOfficerId')}
error={touched.primaryOfficerId && Boolean(errors.primaryOfficerId)}
/>
</Grid>
<Grid item xs={12} sm={6}>
<SearchUsers
name="supportOfficerId"
label="Support Officer"
id="supportOfficerId"
onSelect={change.bind(null, 'supportOfficerId')}
/>
</Grid>
And now my custom component
const Search = (props) => {
const [data, setData] = useState([]);
const [select, setSelect] = useState(0);
const { type: TYPE, name: NAME, label: LABEL, onSelect, filter } = props;
const applyFilter = (data) => {
let result = data;
if (filter) {
result = filter(data);
}
return result;
};
useEffect(() => {
getLookupData(TYPE)
.then((response) => {
setData(response);
})
.catch((error) => {
if (error === HttpStatus.NOT_FOUND) {
setData([]);
} else {
throw error;
}
});
}, [TYPE]);
const options = applyFilter(data).map((item) => (
<MenuItem value={item.id} key={item.id}>
{item[NAME]}
</MenuItem>
));
const handleChange = (event) => {
setSelect(event.target.value);
onSelect && onSelect(event);
};
const { classes } = props;
return (
<FormControl required className={classes.formControl} id={NAME} error={props.error}>
<FormControlLabel control={<InputLabel htmlFor={NAME}>{LABEL}</InputLabel>} />
<Select
name={TYPE}
value={select}
onChange={handleChange}
disabled={props.disabled || options.length === 0}
input={<Input name={TYPE} id={NAME} />}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
{options}
</Select>
</FormControl>
);
};
Below you can see an image of my problem, both PO, and So responsible have an asterisk. I need only PO to have this asterisk but my component does not currently allow for individuals
Simply make your component customizable by passing it a required prop as boolean then in your component make it dynamic :
<FormControl required={props.required}>
// ...
</FormControl>
So now you can use it with an asterisk <SearchUsers required /> or without <SearchUsers required={false} />
Add additional prop required to your Search component and then use it as a prop value for FormControl:
<FormControl required={props.required} />

Categories

Resources