Change of input value with state in React JS - reactjs

I am having 3 text boxes in which users enter values alongwith that I have 3 sliders for which the value is set based on calculation of percentage from the entered values. My problem is I also want to change the text box values based on calculation formulas. So the text box I want them to reflect values with calculation as the slider values change plus user can also type in values.For eg for first textbox I want to calculate value inside with (total-b-c). So with changes in slider values of percentages the values in textboxes should also change. I am unable to do that now-
Here is some supporting code for the same-
const [userValues, setUserValues] = useState({
a: '0',
b: '0',
c: '0',
});
const handleInputChange = (event) =>{
setUserValues({ ...userValues, [event.target.name]: event.target.value });
}
Textboxes-
<div className="container1">
<div className="headingsleft">Enter number of <br></br> invoices</div>
<div>
<h4 style={{fontWeight:500, marginLeft:30,fontSize:19}}>a Invoices</h4>
<br></br>
<br></br>
<TextField label="p.a." type="number" name="a" size="small" className={classes.root} inputProps={{ min: "0" }} variant="outlined" value={userValues.nonedinumber} onChange={handleInputChange} required error={userValues.a=== ""} helperText={userValues.a=== "" ? 'Required' : ' '} ></TextField>
</div>
<div>
<h4 className="headings">b Invoices</h4>
<br></br>
<br></br>
<TextField label="p.a." type="number" name="b" size="small" className={classes.root} inputProps={{ min: "0" }} variant="outlined" value={userValues.b} onChange={handleInputChange} required error={userValues.b=== ""} helperText={userValues.b=== "" ? 'Required' : ' '}/>
</div>
<div>
<h4 style={{fontWeight:500, marginLeft:30,fontSize:19}}>cInvoices</h4>
<br></br>
<br></br>
<TextField label="p.a." type="number" name="c" size="small" className={classes.root} inputProps={{ min: "0" }} variant="outlined" value={userValues.c} onChange={handleInputChange} required error={userValues.c=== ""} helperText={userValues.c=== "" ? 'Required' : ' '}/>
</div>
<div>
<h4 style={{fontWeight:500, marginLeft:30,fontSize:19}}>Total Invoices</h4>
<br></br>
<br></br>
<TextField label="p.a." type="number" size="small" id="total" value={total} disabled variant="outlined" />
</div>
</div>
code for the slider-
const Inputaftercalculate = (props) => {
const classes = useStyles();
return (
<div>
<div className="container2">
<div className="headingsleft">Percentage Distribution
</div>
<div >
<br></br>
<br></br>
<Typography className={classes.slider} id="discrete-slider-always" gutterBottom>
</Typography>
<Slider
defaultValue={20}
getAriaValueText={valuetext}
aria-labelledby="discrete-slider-always"
step={10}
marks={marks}
valueLabelDisplay="on"
value={props.a}
disabled
/>
</div>
<div>
<br></br>
<br></br>
<Typography className={classes.slider} id="discrete-slider-always" gutterBottom>
</Typography>
<Slider
defaultValue={20}
getAriaValueText={valuetext}
aria-labelledby="discrete-slider-always"
step={10}
marks={marks}
valueLabelDisplay="auto"
value={props.b}
/>
</div>
<div>
<br></br>
<br></br>
<Typography className={classes.slider} id="discrete-slider-always" gutterBottom>
</Typography>
<Slider
defaultValue={1}
getAriaValueText={valuetext}
aria-labelledby="discrete-slider-always"
step={10}
marks={marks}
valueLabelDisplay="auto"
value={props.c}
/>
</div>
</div>
</div>
How can I make the input textboxes adjust inside values based on changes in slider values and also let users input in the textbox whenever they need to change values?

First you got get the value and it respective key from the event, then expand it and finally assign the value to the respective key name as shown bellow.
const handleInputChange = e => { const {name, value} = e.target; handleInputChange({ ...userValues, [name]: value, }) }

Related

React Application form data with image uploading field cannot POST to my backend api

First I am trying to post my form data without an image then that data is passed to the backend successfully. then I try to send an image to the backend with form data and then I got an error. image uploading field is a not required field. how I pass the image to the backend with form data.
This is my basic info tab image uploading field
<Grid item xs={6} md={3} sm={4}>
<Controller
name="avatar"
id="avatar"
control={control}
render={({ field }) => (
<TextField
{...field}
className="mt-4 mb-8"
type="file"
onChange={(event) => {
// console.log(event.target.files[0]);
setSelectedImage(event.target.files[0]);
}}
autoFocus
value={selectedImage}
variant="outlined"
size="small"
fullWidth
/>
)}
/>
</Grid>
this is my user.js file return
return (
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)}>
<Root
header={<UserHeader />}
contentToolbar={
<Tabs
value={tabValue}
onChange={handleTabChange}
indicatorColor="primary"
textColor="primary"
variant="scrollable"
scrollButtons="auto"
classes={{ root: 'w-full h-64' }}
>
<Tab className="h-64" label="Basic Info" />
// <Tab className="h-64" label="User Images" />
</Tabs>
}
content={
<div className="p-16 sm:p-16 max-w-2xl">
<div className={tabValue !== 0 ? 'hidden' : ''}>
<BasicInfoTab />
</div>
<div className={tabValue !== 1 ? 'hidden' : ''}>
<ImagesTab />
</div>
{/* <div>
<input type="file" name="file_upload" onChange={onFileChage}/>
</div>
<div>
<button>Submit Data</button>
</div>*/}
</div>
}
innerScroll
/>
</form>
</FormProvider>
);
}
This is my error

Why can't I get values of Date and Text Area in Formik?

I am using Formik and Yup for a form control in React application. I use also Semantic UI. In the application, when I click the submit button, whereas I can read the values from FormField elements and see them on Console, I can not get the value of Date and Text Area elements and they appear blank on Console. How can I solve this out?
Here I define the intial values.
const initialValues = {
jobTitle: { id: "" },
deadline: "",
description: "",
};
Then here I try to get the values from form element
return (
<div>
<Card fluid>
<Card.Content>
<Card.Header>Create A New Job Ad</Card.Header>
<Divider inverted />
<Formik
initialValues={initialValues}
validationSchema={jobAdCreateSchema}
onSubmit={(values) => {
handleSubmit(values);
}}
>
{({ values, setFieldValue }) => (
<div>
<pre>{JSON.stringify(values, undefined, 2)}</pre>
<Form className="ui form">
<FormField>
<label>Job Title</label>
<Dropdown
selection
placeholder="Select a Job Title"
name="jobTitle"
fluid
options={jobTitleOption}
value={values.jobTitle.id}
onChange={(_, { value }) =>
setFieldValue("jobTitle.id", value)
}
/>
</FormField>
<FormField>
<label>Application Deadline</label>
<input
name="deadline"
style={{ width: "100%" }}
type="date"
placeholder="Application Deadline"
value={values.deadline}
onChange={formik.handleChange}
/>
</FormField>
<FormField>
<label>Job Description</label>
<TextArea
name="description"
placeholder="Job Description"
style={{ minHeight: 100 }}
value={values.description}
onChange={formik.handleChange}
/>
</FormField>
<FormField>
<Button color="green" type="submit">
Submit
</Button>
</FormField>
</Form>
</div>
)}
</Formik>
</Card.Content>
</Card>
</div>
);
formik isn't defined, so your assigning an onChange function that doesn't exist.
Destructure handleChange from the argument, then assign it to the inputs like so:
{({ values, setFieldValue, handleChange }) => (
//...
<input
name="deadline"
style={{ width: "100%" }}
type="date"
placeholder="Application Deadline"
value={values.deadline}
onChange={handleChange}
/>
)}
Live demo

How to display data from html response body on textfield or textArea in material UI reactjs?

I have a form. On clicking the 'Evaluate' button, I send a post request. The response of this request is JSON, which I need to display in textField named Output.
How to display data in 'Output' textField?
I just need to display data(which is json in this case) to the text field.
My text field looks like this:
const MyTextField = ({select, values, nullable, min, max, helpertext, ...props}) => {
const [field, meta] = useField(props);
return (
<TextField
select={!!select}
variant="outlined"
margin="dense"
//{...field}
//defaultValue={meta.initialValue}
value={field.value}
error={meta.touched && meta.error}
helperText={(meta.touched && meta.error) ? meta.error : helpertext}
onChange={field.onChange}
onBlur={field.onBlur}
InputProps={{inputProps: {min: min, max: max}}}
{...props}
>
{
values && nullable && values instanceof Array && <MenuItem ><em>None</em></MenuItem>
}
{
values && values instanceof Array && values.map((value, index) => {
return <MenuItem key={value} value={value}>{value}</MenuItem>
})
}
</TextField>
);
};
and form looks like this
return (
<Container fluid className="main-content-container px-4">
<Row noGutters className="page-header py-4">
<PageTitle sm="12" title="Transformer Tester Tool" subtitle="" className="text-center"/>
</Row>
<Paper id="connPageRoot" className={classes.testerRoot}>
<Formik onSubmit={submitEvaluate} initialValues={request}>
<Form>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="json2JsonTransformationConfigDto.template"
name="json2JsonTransformationConfigDto.template"
label="JSLT template"
multiline={true}
rowsMax={4}
fullWidth={true}/>
</div>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="inputs.0"
name="inputs.0"
label="Json payload to be tested"
multiline={true}
rowsMax={4}
fullWidth={true}
/>
</div>
<div className={classes.connPageButton}>
<Button type={"submit"} color="primary" variant="contained">Evaluate</Button> </div>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="outputs.0"
name="outputs.0"
label="Output"
value={result}
multiline={true}
rowsMax={4}
fullWidth={true}
/>
</div>
</Form>
</Formik>
</Paper>
</Container>
);

Save Position of react-draggable objects in react

I am using react-draggable to drag and drop elements. How should I save the elements positions after dragging.
<div className={classes.section}>
<h5>Create Invoice</h5>
{isEditing ? <Button variant="contained" color="primary">Edit</Button> : <Button variant="contained" color="primary">Update</Button>} </label>
<div id="target" onDrop={this.drop} onDragOver={this.allowDrop}>
<Paper className={classes.paper} >
<form>
<Draggable axis="both" bounds="div" disabled={isEditing}>
<CustomInput select variant="outlined" label="To" helperText="Please select your company"/></Draggable>
<Draggable axis="both" bounds="div" disabled={isEditing}><CustomInput name="invoicenumber" label="Invoice Number"/></Draggable>
<Draggable axis="both" bounds="div" disabled={isEditing}><CustomInput id="Date" label="Issue Date" defaultValue="2019-01-01" type="Date" variant="outlined" InputLabelProps={{shrink:true}}/></Draggable>
<TextField id="Date" defaultValue="2019-01-01" type="Date" variant="outlined" InputLabelProps={{shrink:true}}/>
<h5>Item Id</h5> */}
<Draggable axis="both" bounds='div' disabled={isEditing}><CustomInput type="textarea" variant="outlined" label="Description"/></Draggable>
<Draggable axis="both" bounds='Div' disabled={isEditing}>
<CustomInput type="file" variant="outlined" helperText="Attachments" style={{alignContent:"right"}}/>
</Draggable>
</form>
</Paper>
</div>
This is the function for getting the value. Once you get the value then you'll set it a database or localStorage whatever you want.
const eventLogger = (e, data) => {
localStorage.setItem('defaultPosition', { valueX: data.x, valueY: data.y });
};
This function will be called in Dragable by the event onStop.
<Draggable defaultPosition={{ x: 0, y: 0 }} onStop={eventLogger}>
<h2 style={{ cursor: 'grab' }}>
dragable
</h2>
</Draggable>

how to edit a form in react using formik

var fname,
gender,
city = "";
this.props.data.map((row, index) => {
// console.log(index);
if (this.props.selectedVal === index) {
gender = row[0];
fname = row[1];
city = row[2];
}
return [];
});
return (
<div>
<Dialog
open={this.props.open}
onClose={this.handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<h1>Edit User</h1>
<DialogContent>
<DialogContentText id="alert-dialog-description" />
<form onSubmit={handleSubmit}>
<TextField
type="text"
margin="dense"
id="firstname"
label="Name"
onChange={handleChange}
value={fname}
{...props}
/>
<br />
<TextField
type="text"
margin="dense"
id="gender"
label="gender"
onChange={handleChange}
value={gender}
{...props}
/>
<br />
<TextField
type="text"
margin="dense"
id="city"
label="city"
onChange={handleChange}
value={city}
{...props}
/>
</form>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
RESET
</Button>
<Button onClick={this.handleClose} color="primary" autoFocus>
SUBMIT
</Button>
</DialogActions>
</Dialog>
</div>
);
};
render() {
return (
<div align="center">
<Formik
initialValues={{
name: this.props.fname,
gender: this.props.gender,
city: this.props.city
}}
onSubmit={initialValues => console.log("values" + initialValues.name)}
render={this.form}
/>
</div>
);
}
}
Here i am getting the values from table while click on a specific row. I'm getting these values in a dialog using formik. Now i want to edit this formik form. I faced a problem. These values are not edited. How to edit these readonly values.
I added my codesandbox link codesandbox
The way you are doing things is not correct. Some of the functions which you are using never exist.
Here is the working demo of your code Codesandbox demo
Please take a look at the code and understand how it is transformed between two components and feel free to ask me if you have any queries/get stuck understanding the code.

Resources