How to use handleChange in react-numpad widget? - javascript

This is my react-numpad widget I created:
const state = {
number: 0
};
//MAYBE the three following lines are wrong. How to use handleChhange in react-numpad?
const handleChange = e => {
this.setState(e.target.value);
};
const handleBlur = e => {
if (e.target.value === "0") e.target.value = "0";
};
const handleKeypress = e => {
const characterCode = e.key;
if (characterCode === "Backspace") return;
const characterNumber = Number(characterCode);
if (characterNumber < 0) {
e.preventDefault();
}
};
const myTheme = {
fontFamily: "Arial",
textAlign: "center",
header: {
primaryColor: "#263238",
secondaryColor: "#f9f9f9",
highlightColor: "#FFC107",
backgroundColor: "#607D8B"
},
body: {
primaryColor: "#263238",
secondaryColor: "#32a5f2",
highlightColor: "#FFC107",
backgroundColor: "#f9f9f9"
},
panel: {
backgroundColor: "#CFD8DC"
}
};
const priceWidget = ({
step,
precision,
input,
placeholder,
label,
theme,
props,
meta: { touched, error },
...rest
}) => {
return (
<div className="form-group">
<label forname={input.name}>{label}</label> <br />
<NumPad.Number
{...rest}
step={0.1}
precision={2}
placeholder={!input.value ? "please, type a number" : input.value}
selected={input.value ? new NumPad.Number(input.value) : null}
onKeyDown={changedVal => handleKeypress(changedVal)}
onBlur={changedVal => handleBlur(changedVal)}
//IN the FOLLOWING LINE it doesn't work
onChange={value => handleChange(value)}
//BUT IN THIS ONE FOLLOWING LINE WORKS FINE but the field doesn't get the setted value
// onChange={(value) => console.log("price's value",value)}
//ISSUE theme= {myTheme}
//ISSUE onChange={input.onChange}
//ISSUE onBlur={input.onBlur}
className="form-control"
/>
<div className="text-danger" style={{ marginBottom: "20px" }}>
{touched && error}
</div>
</div>
);
};
export default priceWidget;
When I'm executing this line:
onChange={(value) => handleChange(value)}
I've got following issue:
TypeError: Cannot read property 'setState' of undefined
But when I'm executing this another line:
onChange={(value) => console.log("price's value",value)}
It works fine but the field doesn't update with value I selected from my numpad.
e.g. I selected 44 when I'm executing this line:
onChange={(value) => console.log("price's value",value)}
and shows value on console but the field from numpad doesn't update nor show the selected value. It's empty.
So, I have to use handleChange method to change input value but it's not well- implemented.
How can I solve this issue?, anyone knows how can I fix this issue?

I see that App component is a functional component. So this.setState way of updating the state will not work. You will have to use useState hook.
For more information - https://reactjs.org/docs/hooks-state.html

Related

How to reset an object up on button click in react

new to react and I am trying to reset state of an object up on button click. I have am object called setStatusFilters and I wanteed to reset it's data up on button click. Unfortunately, when I do, I got Uncaught TypeError: setStatusFilters is not a function at resetAllFilters. here is my code
ObjectList.js(minimal code)
function ObjectList({
search,
setSearch,
trackingObjects,
loading,
error,
selectedObj,
setSelectedObj,
statusFilters,
setStatusCheckboxFilters,
setStatusFilters,
}) {
const handleClick = React.useCallback((obj) => {
setSelectedObj(obj);
}, []);
console.log(statusFilters, "object");
const resultObjs = filterSearch(
filterObjects(trackingObjects, statusFilters),
search
);
const [res, setReset] = useState(false);
const reset = () => setReset(!setStatusFilters);
const objsWithLocations = resultObjs.filter(
({ location }) =>
location?.[0] !== null &&
location?.[0] !== undefined &&
location?.[1] !== null &&
location?.[1] !== undefined
);
const defaultFilterState = useMemo(
() => makeDefaultFilterState(trackingObjects),
[trackingObjects]
);
const filterOptionsObj = useMemo(
() => makeFilterOptionsObj(trackingObjects),
[trackingObjects]
);
const resetAllFilters = () => {
setStatusFilters("");
};
return (
<Grid container direction="column" sx={classes.Root} <Button
variant="text"
text="Reset"
sx={{
fontSize: "24px",
p: 0,
verticalAlign: "baseline",
ml: "6px",
textTransform: "none",
}}
onClick={() => resetAllFilters()}
/>
</Grid>
);
}
export default ObjectList;
So I have setStatusFilters object and I want to reset it's state to empty when I click Reset button. But I got Uncaught TypeError: setStatusFilters is not a function at resetAllFilters
How can I fix this issue? Thanks

React js Validation textfield

I am trying to make a validation in reactjs.
For example, I have a field called "name" and every time you input a name, this has to be bigger or equal to 2. It works when the name is smaller than 2, but if it's bigger than 2 the message still appears.
Here is my code:
const [data, setData] = React.useState({
nameValid: true,
prenumeValid: true,
check_textInputChange: false,
name: "",
});
const handleValidUser = (val) => {
if (val.length >= 2) {
setData({
...data,
nameValid: true,
});
} else {
setData({
...data,
nameValid: false,
});
}
};
const textInputChange = (val) => {
if (val.length >= 2) {
setData({
...data,
name: val,
nameValid: true,
check_textInputChange: true,
});
} else {
setData({
...data,
name: val,
nameValid: false,
check_textInputChange: false,
});
}
};
<TextField
type="text"
variant="outlined"
label="Nume"
required
fullWidth
autofocus
validate
style={{ marginBottom: "1em" }}
onChange={(val) => textInputChange(val)}
onBlur={(e) => handleValidUser(e)}
/>
{data.nameValid ? null : (
<text>The name has to be at least 2 letters long</text>
)}
onChange has an event parameter, if you want to get the value of the TextField, you should write it as below.
const textInputChange = e => {
const val = e.target.value;
if (val.length > 2) {
setData(...)
} else {
setData(...)
}
}
return (
<TextField
...
onChange={textInputChange}
onBlur={handleValidUser} // as well as onBlur
/>
)
I've created a codesandbox to demonstrate here.
Call the function as below will create an extra render every time the function is called. You should avoid it.
onChange={(val) => textInputChange(val)}
Can you try changing
onChange={(val) => textInputChange(val)}
to this:
onChange={(e) => textInputChange(e.target.value)}
in function textInputChange you are passing event object instead of input value
you have to change onchange handler from:
onChange={(val) => textInputChange(val)}
to
onChange={(val) => textInputChange(val.target.value)}

React wipes the value of an input field

Full example on CodeSandbox
(Css is a bit borked)
Writing anything into the input field or the textarea and then clicking on the select wipes the input field & the textarea, I am not sure why -
It seems that is because I am passing jsx elements to the HoverWrapper element.
When I just inlined the WrapInHover element it behaved as expected. Am I passing Elements in a bad way ?
Adding a key to the passed elements didn't seem to solve the issue ...
const Form = () => {
const selectInit = {
open: false,
initial: true,
selected: 'please select',
};
const selectReducer = (state, action) => {
switch (action.type) {
case 'toggle': {
return { ...state, open: !state.open };
}
case 'select': {
return { ...state, selected: action.selected, open: !state.open, initial: false };
}
}
};
const [selectState, selectDispatch] = useReducer(selectReducer, selectInit);
const selectHelp = selected => selectDispatch({ type: 'select', selected });
const OptionComp = ({ txt, value, onClick }) => (
<Option onClick={onClick} state={selectState} value={value}>
{selectState.open && selectState.selected === value ? null : <HoverBorder />}
{txt}
</Option>
);
const WrapInHover = ({ elements }) => {
const [hover, setHover] = useState(false);
return (
<div
css={css`
position: relative;
`}
onMouseEnter={() => {
setHover(true);
}}
onMouseLeave={() => {
setHover(false);
}}>
{elements}
<HoverBorder hover={hover} />
</div>
);
};
return (
<FormEl>
<WrapInHover elements={<Input key='ContactEmailInput' type='email' required />} />
<Label htmlFor='subject' onClick={() => selectDispatch({ type: 'toggle' })}>
Subject
</Label>
<Select>
<OptionComp
onClick={() => selectHelp('art')}
txt='I want you to paint something !'
value='art'
/>
{selectState.initial && !selectState.open ? (
<OptionComp
txt='Please Select An Option'
value='please select'
onClick={() => selectDispatch({ type: 'toggle' })}
/>
) : null}
</Select>
</FormEl>
);
};
Store value of input and message inside state. Also input will lose focus if your WrapInHover is inside main function
export default function App() {
const Form = () => {
const [formState, setFormState] = useState({ email: "", message: "" });
...
const handleFormDataChange = (e, type) => {
const {target: { value }} = e;
setFormState((prevState) => ({ ...prevState, [type]: value }));
};
return (
<FormEl>
<FormTitle>Contact me</FormTitle>
<Label htmlFor="email">Email</Label>
<WrapInHover
elements={
<Input
key="ContactEmailInput"
type="email"
value={formState.email}
onChange={(e) => handleFormDataChange(e, "email")}
required
/>
}
/>
...
<Label htmlFor="message">Message</Label>
<WrapInHover
elements={
<TextArea
key="ContactMessageTextArea"
name="message"
value={formState.message}
onChange={(e) => handleFormDataChange(e, "message")}
/>
}
/>
CSB Example - I will delete after 24 hours.

MaterialUI Compoent does not AutoComplete when data is available

I can't get my component to show my autosuggestions.
It is observed in the console that my data is available and I sent it to this component using the suggestions prop, using Material UI AutoComplete component feature here I am trying to set my options, and these are changing as I type as it's handled in a parent component, but setting the values does not seem to reflect nor bring up my suggestions. I am very confused. my code is below.
import React, { FunctionComponent, FormEvent, ChangeEvent } from "react";
import { Grid, TextField, Typography } from "#material-ui/core";
import { CreateProjectModel, JobModel } from "~/Models/Projects";
import ErrorModel from "~/Models/ErrorModel";
import Autocomplete from "#material-ui/lab/Autocomplete";
type CreateProjectFormProps = {
model: CreateProjectModel;
errors: ErrorModel<CreateProjectModel>;
onChange: (changes: Partial<CreateProjectModel>) => void;
onSubmit?: () => Promise<void>;
suggestions: JobModel[];
};
const CreateProjectForm: FunctionComponent<CreateProjectFormProps> = ({
model,
errors,
onChange,
onSubmit,
suggestions,
}) => {
const [open, setOpen] = React.useState(false);
const [options, setOptions] = React.useState<JobModel[]>([]);
const loading = open && options.length === 0;
const [inputValue, setInputValue] = React.useState('');
React.useEffect(() => {
let active = true;
if (!loading) {
return undefined;
}
(async () => {
if (active) {
setOptions(suggestions);
}
})();
return () => {
active = false;
};
}, [loading]);
React.useEffect(() => {
if (!open) {
setOptions([]);
}
}, [open]);
const submit = async (event: FormEvent) => {
event.preventDefault();
event.stopPropagation();
await onSubmit();
};
const change = (name: string) => (event: ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
onChange({
[name]: event.target.value,
});
};
const getFieldProps = (id: string, label: string) => {
return {
id,
label,
helperText: errors[id],
error: Boolean(errors[id]),
value: model[id],
onChange: change(id),
};
};
return (
<Autocomplete
{...getFieldProps}
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
getOptionSelected={(option, value) => option.id === value.id}
getOptionLabel={(option) => option.id}
options={options}
loading={loading}
autoComplete
includeInputInList
renderInput={(params) => (
<TextField
{...getFieldProps("jobNumber", "Job number")}
required
fullWidth
autoFocus
margin="normal"
/>
)}
renderOption={(option) => {
return (
<Grid container alignItems="center">
<Grid item xs>
{options.map((part, index) => (
<span key={index}>
{part.id}
</span>
))}
<Typography variant="body2" color="textSecondary">
{option.name}
</Typography>
</Grid>
</Grid>
);
}}
/>
);
};
export default CreateProjectForm;
Example of my data in suggestions look like this:
[{"id":"BR00001","name":"Aircrew - Standby at home base"},{"id":"BR00695","name":"National Waste"},{"id":"BR00777B","name":"Airly Monitor Site 2018"},{"id":"BR00852A","name":"Cracow Mine"},{"id":"BR00972","name":"Toowoomba Updated"},{"id":"BR01023A","name":"TMRGT Mackay Bee Creek"},{"id":"BR01081","name":"Newman Pilot Job (WA)"},{"id":"BR01147","name":"Lake Vermont Monthly 2019"},{"id":"BR01158","name":"Callide Mine Monthly Survey 2019"},{"id":"BR01182","name":"Lake Vermont Quarterly 2019 April"}]
The problem in your code are the useEffects that you use.
In the below useEffect, you are actually setting the options to an empty array initially. That is because you autocomplete is not open and the effect runs on initial mount too. Also since you are setting options in another useEffect the only time your code is supposed to work is when loading state updates and you haven't opened the autocomplete dropdown.
The moment you close it even once, the state is updated back to empty and you won't see suggestions any longer.
React.useEffect(() => {
if (!open) {
setOptions([]);
}
}, [open]);
The solution is simple. You don't need to keep a local state for options but use the values coming in from props which is suggestions
You only need to keep a state for open
const CreateProjectForm: FunctionComponent<CreateProjectFormProps> = ({
model,
errors,
onChange,
onSubmit,
suggestions,
}) => {
const [open, setOpen] = React.useState(false);
const loading = open && suggestions.length === 0;
const [inputValue, setInputValue] = React.useState('');
const submit = async (event: FormEvent) => {
event.preventDefault();
event.stopPropagation();
await onSubmit();
};
const change = (name: string) => (event: ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
onChange({
[name]: event.target.value,
});
};
const getFieldProps = (id: string, label: string) => {
return {
id,
label,
helperText: errors[id],
error: Boolean(errors[id]),
value: model[id],
onChange: change(id),
};
};
return (
<Autocomplete
{...getFieldProps}
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
getOptionSelected={(option, value) => option.id === value.id}
getOptionLabel={(option) => option.id}
options={suggestions}
loading={loading}
autoComplete
includeInputInList
renderInput={(params) => (
<TextField
{...getFieldProps("jobNumber", "Job number")}
required
fullWidth
autoFocus
margin="normal"
/>
)}
renderOption={(option) => {
return (
<Grid container alignItems="center">
<Grid item xs>
{options.map((part, index) => (
<span key={index}>
{part.id}
</span>
))}
<Typography variant="body2" color="textSecondary">
{option.name}
</Typography>
</Grid>
</Grid>
);
}}
/>
);
};
export default CreateProjectForm;
i noticed a few issues with your code, getFieldProps is being called without the id or name params which cause the page to not load. More importantly, you should consider following the autocomplete docs when passing and using props to it. for example:
renderInput={(params) => <TextField {...params} label="Controllable" variant="outlined" />}
i asked a few questions, pls let me know when you can get those answers so i may address all the issues that may come up.
Q1. should the user input provide relevant matches from the name property in your suggestions or just the id? for ex. if i type "lake", do you want to show BRO1182, Lake Vermont Quarterly 2019 April as a match?
Q2. how did you want to address the error case? i see you have a error model, but unsure how you wish to use it to style the autocomplete when an error occurs
Q3. are we missing a submit button? i see the onSubmit function but it's not used in our code.
Q4. is there a particular reason why you need the open and loading states?
below is what i attempted so far to show related matches from user input
import React, { FunctionComponent, FormEvent, ChangeEvent } from "react";
import { Grid, TextField, Typography } from "#material-ui/core";
import { CreateProjectModel, JobModel } from "~/Models/Projects";
import ErrorModel from "~/Models/ErrorModel";
import Autocomplete from "#material-ui/lab/Autocomplete";
type CreateProjectFormProps = {
model: CreateProjectModel;
errors: ErrorModel<CreateProjectModel>;
onChange: (changes: Partial<CreateProjectModel>) => void;
onSubmit?: () => Promise<void>;
suggestions: JobModel[];
};
const CreateProjectForm: FunctionComponent<CreateProjectFormProps> = ({
model,
errors,
// mock function for testing
// consider a better name like selectChangeHandler
onChange = val => console.log(val),
// consider a better name like submitJobFormHandler
onSubmit,
suggestions: options = [
{ id: "BR00001", name: "Aircrew - Standby at home base" },
{ id: "BR00695", name: "National Waste" },
{ id: "BR00777B", name: "Airly Monitor Site 2018" },
{ id: "BR00852A", name: "Cracow Mine" },
{ id: "BR00972", name: "Toowoomba Updated" },
{ id: "BR01023A", name: "TMRGT Mackay Bee Creek" },
{ id: "BR01081", name: "Newman Pilot Job (WA)" },
{ id: "BR01147", name: "Lake Vermont Monthly 2019" },
{ id: "BR01158", name: "Callide Mine Monthly Survey 2019" },
{ id: "BR01182", name: "Lake Vermont Quarterly 2019 April" }
]
}) => {
const [value, setValue] = React.useState<JobModel>({});
const loading = open && options.length === 0;
// this pc of code is not used, why?
const submit = async (event: FormEvent) => {
event.preventDefault();
event.stopPropagation();
await onSubmit();
};
const handleChange = (_: any, value: JobModel | null) => {
setValue(value);
onChange({
[value.name]: value.id
});
};
// consider passing in props instead
const getFieldProps = (id: string, label: string) => {
return {
id,
label,
// not sure what this is
helperText: errors[id],
// not sure what this is
error: Boolean(errors[id]),
value: model[id],
onChange: change(id)
};
};
return (
<Autocomplete
id="placeholder-autocomplete-input-id"
// for selection, use value see docs for more detail
value={value}
onChange={handleChange}
getOptionSelected={(option, value) => option.id === value.id}
getOptionLabel={option => option.id}
options={options}
loading={loading}
autoComplete
includeInputInList
renderInput={params => (
// spreading the params here will transfer native input attributes from autocomplete
<TextField
{...params}
label="placeholder"
required
fullWidth
autoFocus
margin="normal"
/>
)}
renderOption={option => (
<Grid container alignItems="center">
<Grid item xs>
<span key={option}>{option.id}</span>
<Typography variant="body2" color="textSecondary">
{option.name}
</Typography>
</Grid>
</Grid>
)}
/>
);
};
export default CreateProjectForm;
and you can see the code running in my codesandbox by clicking the button below
If I understand your code and issue right, you want -
React.useEffect(() => {
let active = true;
if (!loading) {
return undefined;
}
(async () => {
if (active) {
setOptions(suggestions);
}
})();
return () => {
active = false;
};
}, [loading]);
to run each time and update options, but the thing is, [loading] dependency setted like
const loading = open && suggestions.length === 0;
and not gonna trigger changes.
Consider doing it like so -
const loading = useLoading({open, suggestions})
const useLoading = ({open, suggestions}) => open && suggestions.length === 0;

How to properly update an array inside a react hook state

i've been trying to update the object inside an array that respresents a react state, the object should be updated when the value of an input is changed, I could find a way myself to update it, but i'm not sure enough that it is the proper way to do it because when i open the react dev tools and go to the components tab and click the component that i'm working on, the state doesn't update immidiatly when typing in the input, and in order to see the change i have to click on another component in the dev tool and then go back to the first component and the change is done.
So I'm basically asking if the way i used to update the state is correct and to get some suggestions about better ways to do it so it updates instantly. Thanks
here is the code
the state:
const [items, setItems] = useState([{ name: "", quantity: "", unit: "" }]);
the change handling function (the function that updates the state):
const nameChange = (e, i) => {
const newItems = items;
newItems[i].name = e.target.value;
setItems(newItems);
console.log(items);
};
the inputs:
{
items.map((item, i) => {
return (
<div key={i} className={`mt3 ${classes.root}`}>
<TextField
onChange={e => nameChange(e, i)}
style={{ width: "30%" }}
id="standard-basic"
label="Item name"
/>
<TextField
style={{ width: "25%" }}
id="standard-basic"
label="quantity"
/>
<TextField
style={{ width: "10%" }}
id="standard-basic"
label="Unit"
/>
</div>
);
});
}
const [items, setItems] = React.useState({
name: '',
quantity: '',
unit: ''
});
const handleChange = prop => event => {
setItems({ ...items, [prop]: event.target.value });
};
on your TextFields:
<TextField onChange={handleChange('name')}/>
<TextField onChange={handleChange('quantity')}/>
Update: if items is an array:
const updateItem = (prop, event, index) => {
const old = items[index];
const updated = { ...old, [prop]: event.target.value }
const clone = [...items];
clone[index] = updated;
setItems(clone);
}
on your TextFields:
{items.map((item, i) => (
<div key={i}>
<TextField onChange={e => updateItem('name', e, i)}/>
<TextField onChange={e => updateItem('quantity', e, i)}/>
<TextField onChange={e => updateItem('unit', e, i)}/>
</div>
))}
I got the issue when state is object. I used redux and mapStateToProps and I can't listen the property in object change cause react can not check deeper.
Solution: follow code:
// in reducer file
case 'SAVE_SERVICE_STATE': {
return {
...state,
service: {...payload},
loading: false,
};
}
//listen service state change
useEffect(() => {
if (props.serviceState) {
// do something
}
}, [props.serviceState]);
hope can help someone.

Categories

Resources