MUI Textfield does not update State - reactjs

I have an app which used various inputs which is functioning. For example, I have an initial dataset which is built from an API request, see below:
const [userData, setuserData] = useState([])
const companyuser = useSelector(state=>state.companyuser.currentUser)
useEffect(()=> {
const getUserData = async ()=>{
try{
const companyResponse = await userRequest.get(`companyprofile/findCompany/${companyuser._id}`);
setuserData(companyResponse.data.others)
}catch(err){}
};
getUserData()
},[])
const userInputDataSchema = [
{
id: 1,
label: "companyTitle",
type: "companyTitle",
placeholder: userData.companyTitle,
},
{
id: 2,
label: "surname",
type: "surname",
placeholder: userData.surname
},
{
id: 3,
label: "Email",
type: "email",
placeholder: userData.email
},
{
id: 4,
label: "Position",
type: "position",
placeholder: userData.position
},
{
id: 5,
label: "User Image",
type: "image",
placeholder: userData.userImage
},
{
id: 6,
label: "Professional Bio",
type: "professionalBio",
placeholder: userData.employees
},
{
id: 7,
label: "locationCity",
type: "locationCity",
placeholder: userData.locationCity
},
{
id: 8,
label: "locationCountry",
type: "locationCountry",
placeholder: userData.locationCountry
},
{
id: 9,
label: "whyWork_1",
type: "whyWork_1",
placeholder: userData.whyWork_1
},
];
This data is then mapped across the app, and will update when used. For example:
<UpdateUserDetailsSingular>
{userInputDataSchema.map((input) => (
<FormInput className="formInput" key={input.companyTitle}>
{input.id == 1 ?
<UserInput type={input.type} name="companyTitle" placeholder={input.placeholder}
onChange={handleChange} />
: null}
</FormInput>
))}
</UpdateUserDetailsSingular>
This is functioning. When I use the MUI larger input textfield, it does not update my state. It will dispaly the placeholder text, but if you type it will not handle it.
What is the reason?
{userInputDataSchema.map((input) => (
<div>
{input.id == 9 ?
<TextField
name="whyWork_1"
label="Diversity & Inclusion at Australia Post"
multiline
rows={15}
defaultValue={input.placeholder}
key={input.placeholder}
fullWidth
fullHeight
type={input.type}
handleChange={handleChange}
/> : null}
</div>
))}
</InputBoxContainer>
Does

The reason for this is could be a Mui related misconfiguration in TextField.
defaultValue any The default value. Use when the component is not controlled.
value any The value of the input element, required for a controlled component.
switching from defaultValue to value should do the job.

Related

Why is my input field losing focus when typing a character?

I have a form that have several input fields and for some reason my component y re-rendering everytime y change the value of my input field which produces to the input to lose focus.
ContactForm.js:
const ContactForm = () => {
const [values, setValues ] = useState({
name: '',
lastname: '',
email: '',
confirmEmail: '',
message: ''
});
const inputs = [
{
id: Math.random(),
name: 'name',
type: 'text',
placeholder: 'Name'
},
{
id: Math.random(),
name: 'lastname',
type: 'text',
placeholder: 'Last Name'
},
{
id: Math.random(),
name: 'email',
type: 'email',
placeholder: 'Email'
},
{
id: Math.random(),
name: 'confirmEmail',
type: 'email',
placeholder: 'Confirm Email'
},
{
id: Math.random(),
name: 'message',
type: 'text',
placeholder: 'Message'
}
]
const handleSubmit = (e) => {
e.preventDefault();
}
MY child component, FormInput.js:
import React from 'react'
import './FormInput.css';
/* import { Input } from '../atoms/Input'; */
const FormInput = (props) => {
const { id, onChange, ...inputProps } = props;
return (
<div className='formInput'>
{/* <label htmlFor="">Username</label> */}
{/* <Input {...inputProps} onChange={onChange}/> */}
<input {...inputProps} onChange={onChange} />
</div>
)
}
export default FormInput
const onChange = (e) => {
setValues({...values, [e.target.name]: e.target.value});
}
console.log(values);
return (
<form className='contactForm' onSubmit={handleSubmit}>
{inputs.map((input) => (
<FormInput
key={input.id}
{...input}
value={values[input.name]}
onChange={onChange}
/>
))}
<SubmitBtn/>
</form>
)
}
So is there a solution for this, so that my input field doesn´t lose focus after re-rendering? Or should i prevent re-rendering?
you have 3 options here.
move the input array outside of the component so that it is always the same on every iteration. But if you are fetching this from the server, that is not possible.
you can use a useMemo hook on the input array and make sure to pass an empty array as a dependency array.
remove the Math.random function and maybe use a unique id from the server or for the time being you can use the array index (even though it is not advisable).
I have created a small POC. if you remove the useMemo, the input(s) will lose their focus on every re-render.
Following is the code:
import * as React from 'react';
import './style.css';
export default function App() {
const inputs = React.useMemo(
() => [
{
id: Math.random(),
name: 'name',
type: 'text',
placeholder: 'Name',
},
{
id: Math.random(),
name: 'lastname',
type: 'text',
placeholder: 'Last Name',
},
{
id: Math.random(),
name: 'email',
type: 'email',
placeholder: 'Email',
},
{
id: Math.random(),
name: 'confirmEmail',
type: 'email',
placeholder: 'Confirm Email',
},
{
id: Math.random(),
name: 'message',
type: 'text',
placeholder: 'Message',
},
],
[]
);
const [state, setState] = React.useState({
name: '',
email: '',
message: '',
confirmEmail: '',
lastname: '',
});
const handleChange = (e: any) => {
const value = (e.target as HTMLInputElement).value;
const name = (e.target as HTMLInputElement).name;
setState({
...state,
[name]: value,
});
};
const handleSubmit = () => {
console.log('state', state);
};
return (
<div>
{inputs.map((item) => (
<div key={item.id}>
<label>{item.name}: </label>
<input
name={item.name}
onChange={handleChange}
placeholder={item.placeholder}
/>
</div>
))}
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
It's probably because you are calling Math.random in the body of the ContactForm component. You should never call Math.random() during rendering.
In your case, you can probably move the const inputs to outside the component.

update react state of nested object with array

I want to insert a new object inside the options which is an array property inside the select1 object every time the user clicks on add button, how can I achieve this target, pls reply to this query.
I want to build a simple application where a user enters the options in the select box and can apply conditions based upon the selected option.
const [select1, setSelect1] = useState({
id: uuid(),
type: 'select',
properties: {
label: 'Select1',
options: [
{
id: uuid(),
label: 'text1',
value: {
labelTxt: 'text1',
childOptions: [],
},
},
{
id: uuid(),
label: 'text2',
value: {
labelTxt: 'text2',
childOptions: [],
},
},
],
},
parentId: null,
});
function addOptionsVal() {
setSelect1((prevState) => {
const options = [...prevState.properties.options];
options.splice(1, 0, {
id: uuid(),
label: optionVal,
value: {
labelTxt: optionVal,
childOptions: [],
},
});
console.log(options);
return { ...prevState, options };
});
}
return (
<div>
<select name="" id="">
<option value="">--select--</option>
{select1.properties.options.map((option) => {
return <option>{option.label}</option>;
})}
</select>
</div>
<input
type="text"
value={optionVal}
onChange={(e) => handleValueChange(e)}
/>
<button onClick={addOptionsVal}>Add options</button>
</div>
<div>
<input
type="checkbox"
value="male"
checked={checked}
onChange={toggleCondition}
id="condition"
/>
<label htmlFor="condition">Apply condition</label>
</div>
)
This is the entire code file in case you need
Try this:
function addOptionsVal() {
setSelect1((prevState) => {
return {
...prevState,
properties: {
...prevState.properties,
options: [
...prevState.properties.options,
{
id: uuid(),
label: optionVal,
value: {
labelTxt: optionVal,
childOptions: [],
},
},
],
},
};
});
}
stackblitz
Also, take a look at this question Correct modification of state arrays in React.js

How can i set only value on react select

I am using react-select with the isMulti attribute on a form. For simplicity the data are the following
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
if i select the first two options and then i submit the form, the react-select field will have the following value
reactSelectField: [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' }
]
how can i set the fieldValue to
reactSelectField: ['chocolate', 'strawberry']
which is actually the values of the options and not the whole object?
You could transform values yourself using onChange and a form state
const [values, setValues] = React.useState([]);
<Select
options={options}
value={values.map((value) => ({
label: value,
value,
})}
onChange={(values) => {
setValues(values.map((option) => option.value));
}}
/>
Or create your own wrapper to return the value in the format you expect
const MyMultiSelect = ({ values = [], options = [], onChange, ...props }) => (
<Select
{...props}
value={values.map((value) => ({
label: value,
value,
})}
options={options.map((value) => ({
label: value,
value,
})}
onChange={(values) => {
onChange(values.map((option) => option.value));
}}
/>
)
// Usage
<MyMultiSelect
options={["chocolate", "strawberry", "banana"]}
values={["chocolate", "banana"]}
onChange={(values) => {
console.log(values); // ["chocolate", "banana"]
}}
/>

React component only rendering one item in my object

So I have a react component set up to map through all the items in my array to display them on the page. I'm importing my component onto my homepage and passing the object as a prop from the imported component. However, when I load the page, only one item from the object is being rendered. I'm not entirely sure if I'm passing my object correctly. Any help would be appreciated! Code is below.
This is my Modal component. I'm mapping through the listGroupArray that has a spread operator with my data that is being passed from the home page.
export default function ModalButton({ setData, title, arrayData, dataTitle }) {
const [show, setShow] = useState(false);
const [button, setButton] = useState("Choose...")
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const listGroupArray = [{...arrayData}]
const changeButton = e => setButton(e)
return (
<>
<h5 className="inputFont text-center">{title}</h5>
<Button style={{ backgroundColor: "black", opacity: "1", color: "white", borderColor: "red" }} variant="primary" className="w-100 mb-4 inputFont" onClick={handleShow}>
{button}
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton className="modal-bg inputFont">
{dataTitle}
</Modal.Header>
<Modal.Body className="modal-bg">
<ListGroup>
{listGroupArray.map(item => (
<ListGroup.Item key={item.id} className="modal-bg">
<Button
style={{
backgroundColor: "black",
opacity: ".8",
color: "white",
borderColor: "red",
}}
className="inputFont w-100"
name={item.name}
value={item.value}
onClick={(e) => {
setData(item.value);
changeButton(item.name);
handleClose();
}}
>
{item.name}
</Button>
</ListGroup.Item>
))}
</ListGroup>
</Modal.Body>
</Modal>
</>
);
}
This is my homepage where I'm passing the array data as an object. I'm pretty sure this is where I'm going wrong. When I load the page, the component should render all the data in the object, however it's only rendering the last data, Classics.
<Modal title="Genre"
dataTitle="Pick A Genre"
setData={setGenrelist}
arrayData={
{
id: 1,
name: "Action and Adventure",
value: "10673,10702,11804,11828,1192487,1365,1568,2125,2653,43040,43048,4344,46576,7442,75418,76501,77232,788212,801362,899,9584"
},
{
id: 2,
name: "Musicals",
value: "13335,13573,32392,52852,55774,59433,84488,88635"
},
{
id: 3,
name: "Sci-Fi",
value: "1492,108533,11014,1372,1568,1694,2595,2729,3327,3916,47147,4734,49110,50232,52780,52849,5903,6000,6926,852491"
},
{
id: 4,
name: "Fantasy",
value: "9744"
},
{ id: 5,
name: "Thrillers",
value: "10306,10499,10504,10719,11014,11140,1138506,1321,1774,3269,43048,46588,5505,58798,65558,6867,75390,78507,799,852488,8933,98911,9147,972"
},
{
id: 6,
name: "Anime",
value: "10695,11146,2653,2729,3063,413820,452,6721,9302,7424"
},
{
id: 7,
name: "Children and Family",
value: "10056,27480,27950,28034,28083,28233,48586,5455,561,6218,6796,6962,78120,89513,783"
},
{
id: 8,
name: "Comedies",
value: "1009,10256,10375,105,10778,11559,11755,1208951,1333288,1402,1747,17648,2030,2700,31694,3300,34157,3519,3996,4058,4195,43040,4426,4906,52104,52140,52847,5286,5475,5610,56174,58905,59169,61132,61330,6197,63092,63115,6548,711366,7120,72407,7539,77599,77907,78163,78655,79871,7992,852492,869,89585,9302,9434,9702,9736"
},
{
id: 9,
name: "Documentaries",
value: "10005,10105,10599,1159,15456,180,2595,2616,2760,28269,3652,3675,4006,4720,48768,49110,49547,50232,5161,5349,55087,56178,58710,60026,6839,7018,72384,77245,852494,90361,9875"
},
{
id: 10,
name: "Dramas",
value: "11,11075,11714,1208954,1255,12995,13158,2150,25955,26009,2696,2748,2757,2893,29809,3179,31901,34204,3653,3682,384,3916,3947,4282,4425,452,4961,500,5012,52148,52904,56169,58755,58796,59064,6206,62235,6616,6763,68699,6889,711367,71591,71591,72354,7243,7539,75459,76507,78628,852493,89804,9299,9847,9873,5763"
},
{
id: 11,
name: "Sports",
value: "180,25788,4370,5286,7243,9327"
},
{
id: 12,
name: "Horror",
value: "10695,10944,1694,42023,45028,48303,61546,75405,75804,75930,8195,83059,8711,89585"
},
{
id: 13,
name: "Romance",
value: "29281,36103,502675"
},
{
id: 14,
name: "Classics",
value: "10032,11093,13158,29809,2994,31273,31574,31694,32392,46553,46560,46576,46588,47147,47465,48303,48586,48744,76186"
}
}
/>
screenshot of the homepage
This image shows the component only rendering one data item which is Classics. Any advice on how to get all data rendered would be greatly appreciated! Thanks!
The error is in how you referenced the arrayData and the problematic curly brackets you used on an array. In your JSX code, you have a syntax error, you are supposed to enclose arrays in curly brackets, or better still just separate them to their own variable.
Your JSX should then look something like this:
function JSX(props) {
const arrayData = [
{
id: 1,
name: "Action and Adventure",
value:
"10673,10702,11804,11828,1192487,1365,1568,2125,2653,43040,43048,4344,46576,7442,75418,76501,77232,788212,801362,899,9584",
},
{
id: 2,
name: "Musicals",
value: "13335,13573,32392,52852,55774,59433,84488,88635",
},
{
id: 3,
name: "Sci-Fi",
value:
"1492,108533,11014,1372,1568,1694,2595,2729,3327,3916,47147,4734,49110,50232,52780,52849,5903,6000,6926,852491",
},
{
id: 4,
name: "Fantasy",
value: "9744",
},
{
id: 5,
name: "Thrillers",
value:
"10306,10499,10504,10719,11014,11140,1138506,1321,1774,3269,43048,46588,5505,58798,65558,6867,75390,78507,799,852488,8933,98911,9147,972",
},
{
id: 6,
name: "Anime",
value: "10695,11146,2653,2729,3063,413820,452,6721,9302,7424",
},
{
id: 7,
name: "Children and Family",
value:
"10056,27480,27950,28034,28083,28233,48586,5455,561,6218,6796,6962,78120,89513,783",
},
{
id: 8,
name: "Comedies",
value:
"1009,10256,10375,105,10778,11559,11755,1208951,1333288,1402,1747,17648,2030,2700,31694,3300,34157,3519,3996,4058,4195,43040,4426,4906,52104,52140,52847,5286,5475,5610,56174,58905,59169,61132,61330,6197,63092,63115,6548,711366,7120,72407,7539,77599,77907,78163,78655,79871,7992,852492,869,89585,9302,9434,9702,9736",
},
{
id: 9,
name: "Documentaries",
value:
"10005,10105,10599,1159,15456,180,2595,2616,2760,28269,3652,3675,4006,4720,48768,49110,49547,50232,5161,5349,55087,56178,58710,60026,6839,7018,72384,77245,852494,90361,9875",
},
{
id: 10,
name: "Dramas",
value:
"11,11075,11714,1208954,1255,12995,13158,2150,25955,26009,2696,2748,2757,2893,29809,3179,31901,34204,3653,3682,384,3916,3947,4282,4425,452,4961,500,5012,52148,52904,56169,58755,58796,59064,6206,62235,6616,6763,68699,6889,711367,71591,71591,72354,7243,7539,75459,76507,78628,852493,89804,9299,9847,9873,5763",
},
{
id: 11,
name: "Sports",
value: "180,25788,4370,5286,7243,9327",
},
{
id: 12,
name: "Horror",
value:
"10695,10944,1694,42023,45028,48303,61546,75405,75804,75930,8195,83059,8711,89585",
},
{
id: 13,
name: "Romance",
value: "29281,36103,502675",
},
{
id: 14,
name: "Classics",
value:
"10032,11093,13158,29809,2994,31273,31574,31694,32392,46553,46560,46576,46588,47147,47465,48303,48586,48744,76186",
},
];
return (
<Modal
title="Genre"
dataTitle="Pick A Genre"
setData={(data) => console.log(data)}
arrayData={arrayData}
/>
);
}
The next bug you had was in using the spread operator. While arrays are technically objects in JavaScript they can't be spread with curly braces. This [{...arrayData}] is syntactically incorrect. Instead it should be [...arrayData]. With these in place, your code should run correctly.
I made a sandbox of your code in a working state for reference, check it out here:
https://codesandbox.io/s/young-snowflake-efqwk?file=/src/ModalButton.js:877-883

Cannot use multiple radiogroups in react-materialize

So, I am building an avatar creator for my application, and I have a Carousel that holds multiple RadioGroups, I can slide to the new radiogroup, but when I click on any of the other radio groups (except for the first one) and it will only target the value from the first one.
<Carousel options={{ fullWidth: true, indicators: true }} className="black-text center">
<div>
<RadioGroup
name="hair"
label="Hair Selection"
value={this.state.avatar.topType}
onChange={this.handleAvatarChange}
options={[{ label: 'Eyepatch', value: 'Eyepatch' }, { label: 'Long
Hair', value: 'LongHairStraight2' }, { label: 'Medium Hair', value:
'LongHairNotTooLong' }, { label: 'Short Hair', value:
'ShortHairShortFlat' }, { label: 'Short Dreads', value:
'ShortHairDreads01' }, { label: 'Balding', value: 'ShortHairSides'
}]}
/>
</div>
<div>
<RadioGroup
name="hairColor"
label="Hair Selection"
value={this.state.avatar.hairColor}
onChange={this.handleAvatarChange}
options={[{ label: 'Brown', value: 'Brown' }, { label: 'Blonde',
value: 'Blonde' }, { label: 'Red', value:
'Red' }, { label: 'Gray', value:
'Gray' }, { label: 'Black', value:
'Black' }, { label: 'Auburn', value: 'Auburn'
}]}
/>
</div>
</Carousel>
handleAvatarChange = (event) => {
let selection = event.target.value;
let type = event.target.name;
console.log(selection, 'event')
console.log(type, 'type');
let avatarCopy = { ...this.state.avatar };
if (type === 'hair') {
avatarCopy.topType = selection
this.setState({ avatar: avatarCopy });
} else if (type === 'hairColor') {
avatarCopy.hairColor = selection;
this.setState({ avatar: avatarCopy });
}
}
I expect that when I slide to the next slide on the carousel, that I can change the state based on the type that was passed back to my handleAvatarChange function. Instead, all of the slides are changing the values based on the first slide.
It seems like the autogenerated id numbering for the options resets to 0 for each radiogroup, even if they are in the same DOM.
Therefore, each n input of the radio groups has the same id (<input id="radio0" type="radio" value="1" checked="">).
I have reported the bug here.
As a workaround, I'm requesting an "id" prop, and if not found, concatenating the component's name to the index to build the id's.
var RadioGroup = function RadioGroup(_ref) {
var onChange = _ref.onChange,
withGap = _ref.withGap,
disabled = _ref.disabled,
name = _ref.name,
radioClassNames = _ref.radioClassNames,
value = _ref.value,
options = _ref.options;
return _react.default.createElement(_react.default.Fragment, null, options.map(function (radioItem, idx) {
return _react.default.createElement("label", {
className: radioClassNames,
htmlFor: radioItem.id ? radioItem.id : "radio".concat(radioItem.name).concat(idx),
key: radioItem.id ? radioItem.id : "radio".concat(radioItem.name).concat(idx)
}, _react.default.createElement("input", {
id: radioItem.id ? radioItem.id : "radio".concat(radioItem.name).concat(idx),
value: radioItem.value,
type: "radio",
checked: radioItem.value === value,
name: name,
onChange: onChange,
disabled: disabled,
className: (0, _classnames.default)({
'with-gap': withGap
})
}), _react.default.createElement("span", null, radioItem.label));
}));
};

Resources