State is empty even have setted up with data - javascript

I am trying to fetch the data from the database and storing it in a state but when I console log my state, no data has been stored in the state but when I console the data itself, it returns what I expected to have. This is my code;
import React, { useContext, useEffect, useState } from 'react';
import { Field, Form, Formik, useField } from 'formik';
import * as Yup from 'yup';
import {
Button,
Box,
makeStyles,
Grid,
Typography,
Divider,
FormHelperText,
Select,
MenuItem,
InputLabel,
FormControl,
} from '#material-ui/core';
import {
MuiPickersUtilsProvider,
KeyboardDateTimePicker,
} from '#material-ui/pickers';
import DateFnsUtils from '#date-io/date-fns';
import 'date-fns';
// Yup validation Schema
const validationSchema = Yup.object().shape({
date: Yup.date().required('Please enter valid date').nullable(),
teamOne: Yup.string().required('Please select team'),
teamTwo: Yup.string().required('Please select team'),
});
// This is a custom date field using Formik
const DateTimeField = ({ field, form, ...props }) => {
const currentError = form.errors[field.name];
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDateTimePicker
clearable
disablePast
name={field.name}
value={field.value}
format="MM/dd/yyyy"
helperText={currentError}
error={!!currentError}
onError={(error) => {
if (error !== currentError) {
form.setFieldError(field.name, error);
}
}}
onChange={(date) => form.setFieldValue(field.name, date, true)}
{...props}
/>
</MuiPickersUtilsProvider>
);
};
// Custom <Select> field
const TeamSelection = ({ name, ...props }) => {
const [field, meta] = useField(name);
const errorText = meta.error && meta.touched ? meta.error : '';
return (
<>
<Select
name={field.name}
{...field}
fullWidth
error={!!errorText}
{...props}
>
{props.children}
</Select>
<FormHelperText error>{errorText}</FormHelperText>
</>
);
};
export default function AddMatch() {
const classes = useStyles();
const fetchContext = useContext(FetchContext);
const [team, setTeam] = useState([]);
useEffect(() => {
const getTeam = async () => {
try {
const { data } = await fetchContext.authAxios.get('get-all-teams');
setTeam(data);
} catch (error) {
console.log(error);
}
};
getTeam();
}, [fetchContext]);
console.log(team);
return (
<Formik
initialValues={{ date: new Date(), teamOne: '', teamTwo: '' }}
validationSchema={validationSchema}
onSubmit={(values) => {
if (values.teamOne === values.teamTwo) {
return console.log('Teams must not be the same!');
}
return console.log(values);
}}
>
{() => (
<Form noValidate>
<Grid>
<Typography>
Add Match
</Typography>
</Grid>
<Divider />
<Box>
<Grid>
<Grid>
<Field
name="date"
label="Set date and time"
component={DateTimeField}
/>
</Grid>
<Grid>
<Grid>
<FormControl>
<InputLabel>
Team A
</InputLabel>
<TeamSelection name="teamOne">
<MenuItem value=""> </MenuItem>
{team.map((item) => (
<MenuItem value={item.teamName} key={item._id}>
{item.teamName}
</MenuItem>
))}
</TeamSelection>
</FormControl>
</Grid>
<Grid>
<FormControl>
<InputLabel>
Team B
</InputLabel>
<TeamSelection name="teamTwo">
<MenuItem value=""> </MenuItem>
{team.map((item) => (
<MenuItem value={item.teamName} key={item._id}>
{item.teamName}
</MenuItem>
))}
</TeamSelection>
</FormControl>
</Grid>
</Grid>
<Box>
<Button type="submit">
Submit
</Button>
</Box>
</Grid>
</Box>
</Form>
)}
</Formik>
)}
I'm using Material UI and Formik.
It only logged an empty array "[]" or it makes an error, (.map is not a function). I tried to set the state as an Object but there is still no data being stored with the state.

Check the post request in your res.status(200).json() or res.send() or res.json(). Don't use brackets inside .json() or .send(), in your res or response, for example:
.json({}) // Don't use brackets if you don't want to send your data as an Object
If ever you want it to be object, then call the array which is called data like
useEffect(() => {
const getTeam = async () => {
try {
const { teamsData } = await fetchContext.authAxios.get('get-all-teams');
setTeam(teamsData.data);
} catch (error) {
console.log(error);
}
};
getTeam();
}, [fetchContext]);
destructure the teamsData if you have passed it as an Object on purpose.

Related

React Autocomplete with Material UI

I'm implementing a component Autocomplete using Material UI library.
But there's a problem - I'm not sure how to pass value and onChange properly, because I have a custom implementation of TextField that requires value and onChange as well. Should I pass value and onChange twice - to Autocomplete and TextField? Or maybe there's a better solution? Would appreciate any help!
Here's my code:
import { Autocomplete as MuiAutocomplete } from '#material-ui/lab'
import { FormControl } from 'components/_helpers/FormControl'
import { useStyles } from 'components/Select/styles'
import { Props as TextFieldProps, TextField } from 'components/TextField'
export type Props = Omit<TextFieldProps, 'children'> & {
options: Array<any>
value: string
onChange: (value: string) => void
disabled?: boolean
}
export const Autocomplete = (props: Props) => {
const classes = useStyles()
return (
<FormControl
label={props.label}
error={props.error}
helperText={props.helperText}
>
<MuiAutocomplete
options={props.options}
// value={props.value}
// onChange={event =>
// props.onChange((event.target as HTMLInputElement).value as string)
// }
classes={{
option: classes.menuItem,
}}
disabled={props.disabled}
getOptionLabel={option => option.label}
renderInput={params => (
<TextField
{...params}
placeholder={props.placeholder}
value={props.value}
onChange={props.onChange}
/>
)}
renderOption={option => {
return <Typography>{option.label}</Typography>
}}
/>
</FormControl>
)
}```
Material UI has props built in to handle the state of the Autocomplete vs input values.
You can see it in use in the docs here: https://material-ui.com/components/autocomplete/#controllable-states
In your example, you would want to add the inputChange and onInputChange props to the Autocomplete component. These will get passed down to your TextField through the params passed to the renderInput function.
So your final code would look something like the below snippet copied from the linked documentation:
<Autocomplete
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={options}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Controllable" variant="outlined" />}
/>
import React, { useEffect, useState } from "react";
import { Autocomplete } from "#mui/material/node";
import { Controller, useFormContext } from "react-hook-form";
import { TextField } from "#mui/material";
import PropTypes from "prop-types";
const valueFunc = (arr, id) => {
const temp = arr.length > 0 && arr?.find((element) => element.id === id);
return temp;
};
AutocompleteSearch.propTypes = {
options: PropTypes.arrayOf({
title: PropTypes.string,
id: PropTypes.string,
}),
name: PropTypes.string,
};
export default function AutocompleteSearch({
name,
options,
label,
id,
...other
}) {
const [temp, setTemp] = useState({});
const { control, setValue } = useFormContext();
useEffect(async () => {
const found = valueFunc(options, id);
await setTemp(found);
}, [options, id]);
return (
<Controller
control={control}
name={name}
rules={{ required: true }}
render={({ fieldState: { error } }) => (
<>
<div >
<Autocomplete
id="controllable-states-demo"
onChange={(_, v) => {
setValue(name, v?.id);
setTemp(v);
}}
onBlur={(e) => {
e.target.value == "" && setValue(name, "");
}}
value={temp}
options={options}
getOptionLabel={(item) => (item.title ? item.title : "")}
renderInput={(params) => (
<>
<TextField
{...params}
label={label}
InputLabelProps={{
style: {
fontSize: "14px",
fontWeight: "400",
color: "#FF5B00",
},
}}
size="small"
error={temp === null && !!error}
helperText={temp === null && error?.message}
{...other}
/>
</>
)}
/>
</div>
</>
)}
/>
);
}
<AutocompleteSearch
name="pharmacy_group_title"
label="Pharmacy Group"
options={pharmacyGroups} // Array {id , title}
id={defaultValues?.pharmacy_group_title} // ID
/>

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

Dropdown filter is showing incorrect result in React

The display should show the result as per the values selected in checkboxes and dropdown. While checkboxes are working well and displaying result accordingly, the dropdown on selection do not show the correct display. It only shows the display as per the last clicked value and not the current one.
Also the displays are incorrect in case I select dropdown first and then apply checkbox filter.
Here is my code:
import { React, useState } from "react";
import BookData from "../data/bookData.json";
import Card from "#material-ui/core/Card";
import CardActions from "#material-ui/core/CardActions";
import CardContent from "#material-ui/core/CardContent";
import { Checkbox, Typography } from "#material-ui/core";
import Grid from "#material-ui/core/Grid";
import "../style/search.css";
import FormGroup from "#material-ui/core/FormGroup";
import FormControlLabel from "#material-ui/core/FormControlLabel";
const BookDisplay = (props) => {
const allBooks = BookData.book.map((books) => {
return books;
});
const [edition, setEdition] = useState(""); // dropdown state
const [activeFilter, setActiveFilter] = useState([]);
const [filteredResult, setFilteredResult] = useState(allBooks);
//Building DropDown Filter
const uniqueEditions = [
...new Set(
BookData.book.map((allEditions) => {
return allEditions.edition;
})
)
]; // filters out all the unique edition of the books
const editionDropdown = uniqueEditions.map((edition) => (
<option value={edition}>{edition}</option>
));
editionDropdown.unshift(<option value="">All Editions</option>);
//Making a checkbox
const uniqueGenre = [
...new Set(
BookData.book.map((bookGenre) => {
return bookGenre.genre;
})
)
];
//adding checked =false falue for every object
uniqueGenre.map((obj) => ({ ...obj, Active: false }));
// filtering result based on checkbox value
const handleCheckBox = (filter) => {
const newFilter = activeFilter.includes(filter)
? activeFilter.filter((f) => {
return f !== filter;
})
: [...activeFilter, filter];
setActiveFilter(newFilter);
console.log(allBooks);
const filteredList =
newFilter.length > 0
? allBooks.filter((item) => newFilter.includes(item.genre))
: allBooks;
console.log(filteredList);
setFilteredResult(filteredList);
console.log("filteredresult in checkbox", filteredResult);
};
//handling dropdown change
const handleDropDownChange = (event, name) => {
event.preventDefault();
setEdition({
[name]: event.target.value
});
const searchedBooks = filteredResult.filter((filteredBooks) => {
return Object.entries(edition).every(([key, value]) => {
if (!value) return true;
console.log(`${key}: ${value}`);
return filteredBooks[key] === value;
});
});
setFilteredResult(searchedBooks);
};
return (
<div>
<form className="Search">
<label>Edition</label>
<select
defaultValue={edition}
onChange={(e) => handleDropDownChange(e, "edition")}
>
{editionDropdown}
</select>{" "}
</form>
<Grid>
{uniqueGenre.map((genre, index) => (
<FormGroup key={index}>
<FormControlLabel
control={<Checkbox name={genre} />}
label={genre}
value={genre}
checked={genre.Active}
onChange={() => handleCheckBox(genre)}
color="Primary"
/>
</FormGroup>
))}
<Grid></Grid>
<Grid xs={9}>
<div className="container">
{filteredResult.map((bookData) => (
<Card key={bookData.id}>
<CardActions>
<CardContent>
<Typography className="avatar">
<div>
<img src={bookData.imgUrl} alt="img" />
</div>
<span>
<u> {bookData.title}</u>
</span>
</Typography>
<br />
<div className="book-Info">
<Typography>
<b>Price:</b> {bookData.price}
</Typography>
<Typography>
<b>Author:</b>
{bookData.author}
</Typography>
<Typography>
<b>Year:</b>
{bookData.year_written}
</Typography>
<Typography>
<b>Edition:</b> {bookData.edition}
</Typography>
<Typography>
<b>Genre:</b> {bookData.genre}
</Typography>
</div>
</CardContent>
</CardActions>
</Card>
))}
</div>
</Grid>
</Grid>
</div>
);
};
export default BookDisplay;
Code Sample

Issue in react context api

Facing issues in react context api, getting undefined while transferring anything using context api.
getting this error, getting undefined when sending functions through context api.
*** Context.js
import React, { useReducer, createContext } from "react";
import contextReducer from "./contextReducer";
const initialState = [];
export const ExpenseTrackerContext = createContext(initialState);
export function Provider({ children }) {
const [transactions, dispatch] = useReducer(contextReducer, initialState);`enter code here`
const deleteTransaction = (id) =>
dispatch({ type: "DELETE_TRANSACTION", payload: id });
const addTransaction = (transaction) =>
dispatch({ type: "ADD_TRANSACTION", payload: transaction });
return (
<ExpenseTrackerContext.Provider
value={{
deleteTransaction,
addTransaction,
transactions,
}}
>
{children}
</ExpenseTrackerContext.Provider>
);
}***
getting undefined in this file while using the function in this file Form.js > and getting error addTransaction is not a function
*** Form.js
import React, { useState, useContext } from "react";
import {
TextField,
Typography,
Grid,
FormControl,
InputLabel,
Select,
MenuItem,
Button,
} from "#material-ui/core";
import { ExpenseTrackerContext } from "../../context/context";
import { v4 as uuidv4 } from "uuid";
import useStyles from "./styles";
const initialState = {
amount: "",
category: "",
type: "Income",
date: new Date(),
};
const Form = (props) => {
const classes = useStyles();
const [formData, setFormData] = useState(initialState);
// console.log(useContext(ExpenseTrackerContext));
const { addTransaction } = useContext(ExpenseTrackerContext);
console.log("context: " + ExpenseTrackerContext.displayName);
console.log("add: " + typeof addTransaction);
const createTransaction = () => {
const transaction = {
...formData,
amount: Number(formData.amount),
id: uuidv4(),
};
addTransaction(transaction);
setFormData(initialState);
};
return (
<Grid container spacing={2}>
<Grid item xs={12}>
<Typography align="center" variant="subtitle2" gutterBottom>
...
</Typography>
</Grid>
<Grid item xs={6}>
<FormControl fullWidth>
<InputLabel>Type</InputLabel>
<Select
value={formData.type}
onChange={(e) => setFormData({ ...formData, type: e.target.value })}
>
<MenuItem value="Income">Income</MenuItem>
<MenuItem value="Expense">Expense</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item xs={6}>
<FormControl fullWidth>
<InputLabel>Category</InputLabel>
<Select
value={formData.category}
onChange={(e) =>
setFormData({ ...formData, category: e.target.value })
}
>
<MenuItem value="business">Business</MenuItem>
<MenuItem value="Salary">Salary</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item xs={6}>
<TextField
type="number"
label="Amount"
fullWidth
value={formData.amount}
onChange={(e) => setFormData({ ...formData, amount: e.target.value })}
/>
</Grid>
<Grid item xs={6}>
<TextField
type="date"
label=" "
fullWidth
value={formData.date}
onChange={(e) => setFormData({ ...formData, date: e.target.value })}
/>
</Grid>
<Button
className={classes.button}
variant="outlined"
color="primary"
fullWidth
onClick={createTransaction}
>
Create
</Button>
</Grid>
);
};
export default Form; ***
why?
you are forget to call the context with in From.js. Because you are created the context hook with same page
Better create the context file seperate js file
context.js
import React,{createContext} from 'react';
export const ExpenseTrackerContext = createContext(null);
Contextr.js
import {ExpenseTrackerContext} from './context.js' // path of context.js
From.js
import React,{useContext} from 'react';
import {ExpenseTrackerContext} from './context.js' // path of context.js
export default function From(props){
const expContext = useContext(ExpenseTrackerContext);
expContext.addTransaction()// you could call like this
...
Updated - React Doc
Accepts a context object (the value returned from React.createContext)
and returns the current context value for that context. The current
context value is determined by the value prop of the nearest
<MyContext.Provider> above the calling component in the tree.
Context passing value only with in tree of children. please check Form.js is execute inside the {children} component of context provider. if you are using parallel or sibling component its does not work
<ExpenseTrackerContext.Provider
value={{
deleteTransaction,
addTransaction,
transactions,
}}
>
{children} // From.js present in this children in any one of the tree otherwise undefined (value only passed inside the provider component tree)
</ExpenseTrackerContext.Provider>

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