How to add two value in react? - javascript

I am preparing a demo of add function where user enter two values in input field and result will be display on third field
But I am not able to show that result
Here is my code
https://codesandbox.io/s/flamboyant-smoke-ewkbd
return (
<div className="App">
Add Demo
<br />
<br />
<br />
{state.map(({ type, label, name }) => {
if (type === "text") {
return (
<div>
<label>{label}</label>
<input type="text" onChange={handleChange} name={name} />
</div>
);
}
})}
</div>
);
When I entered 2 in first field and 2 in second field .Expected output will be 4 in result field

I agree with your idea of using State, but better use form value where you can freely update your values.
If you need calculation, you can use number type rather than text
Use setForm for update value
Provide value with form values and show result with combination of first and second.
https://codesandbox.io/s/nice-violet-tv0vw

Related

React Formik get form state's values

I have a form with two fields name and age. I know when user fill these two fields and hit the submit button I can get the values for these two fields.
But what I want is, I have a button call show filled values. When your press that button I want to see the user-filled values in the form. For example, if he fills name as 'Tom' and age as 85. I want to see that. But right now what I am getting is the empty initial values object.
My Code
How do I achieve this using Reactjs?
U can get the filled fields using Formiks props provided by the Formik.
The values prop provided by the formik will gives the filled fields values. Initially it will be the empty object . After you start filling the fields, the values object will be updated accordingly.
To know more What Props can Formik provide ?
visit :- https://formik.org/docs/api/formik#touched--field-string-boolean-
Hope the below code snippet will be useful for you.
<Formik
initialValues={{}}
validationSchema={() => Yup.object().shape({`enter your validation keys here`})}
onSubmit={(values) => {
console.log('values after submit', values);
}}
>
{(formikProps) => {
const { values, handleChange } = formikProps;
return (
<Form>
<label>
name
<input name="name" onChange={handleChange} />
</label>
<label>
age
<input name="age" type="number" onChange={handleChange} />
</label>
<button
type="button"
onClick={() => {
console.log('show filled fields', values);
}}
>
Show Filled Fields
</button>
<button type={'submit'}> Submit</button>
</Form>
);
}}
</Formik>

How to validate react input fields with some custom validation

I am working with react and making some new input fields dynamically, and using React-gook-form for validation.
What I am doing is -
I have one dropdown in which I have numbers as dropdown, like 1,2,3,4
So which ever dropdown user is selecting I am creating that much input field
if user selects 3 then 3 input fields
What I am trying to achieve is
When user create two input fields i do not want both of them to have same input.
Like if first input is having D as input then the second one should not take D in second one.
PS- here just for minimal code i am creating only one set of input, like first name
It can be when i select 2 then I can create two set of inputs having Fname and Lname in each set so there both fname should not take same value and same goes for lname.
What I have done
this one to hold the state, initial one is selected and one input is created.
const [initialSet, setinitialSet] = useState(1);
On select change doing this
const Select_change = (e) => {
let val = parseInt(e.target.value);
setinitialSet(val);
};
Now using that initial state to loop my elements to create input fields
<div className="row">
{[...Array(initialSet).keys()].map((li, index) => (
<div className="col-12 col-sm-12 col-md-8 col-lg-4 col-xl-4">
<div className="form-group">
<input
type="text"
name={`data[${index}].name`}
id={"name" + index}
className="form-control"
placeholder="F Name"
ref={register({ required: `F name ${index} is required` })}
/>
<label" htmlFor={"name" + index}>
F Name
</label>
{errors.data && errors.data[index] && errors.data[index].name && (
<div>
<span className="text-danger">
{errors.data[index].name.message}
</span>
</div>
)}
</div>
</div>
))}
</div>
Now I just want to validate the fname so that two input fields of f name should not have same input.
Code sandbox link
I have full working code in my code sandbox
You can use an array of inputs so when you select 3 you create an array with 3 elements that will contain the data.
const [initialSet, setinitialSet] = useState([]);
and here's the creation process:
const Select_change = (e) => {
let val = parseInt(e.target.value);
setinitialSet( new Array(val));
}
optionally you can initialise the array to zeros if you want
setinitialSet( new Array(val).fill(0) );
When you loop over the inputs you will use the index of the element in the array.
You can even store names and errors in each element of the element if you want a complicated logic.

Updated - Not able to press backspace after programmatically changing Input Fields

I have an element as follows :
<SearchBar>
<InputText
type="search"
placeholder="Search for tasks in the BOQ..."
value={ taskName }
onChange={this.handleChangeInputTaskName}
/>
</SearchBar>
I want to keep the onChange method 'handleChangeInputTaskName' in place so the user can type in whatever he wants and I am able to process the input.
However, after processing the input from the user, I also want to be able to programmatically fill in the target value for the input field. Is it possible to achieve this?
=============================================================================
I was able to able to manually fill in the input field by just setting the state of the taskName to the desired value. However now it doesn't allow me to press backspace.
You can do this like this:
<SearchBar>
<InputText
type="search"
placeholder="Search for tasks in the BOQ..."
value={ taskName }
onChange={(value) => this.handleChangeInputTaskName('taskName ', value)}
/>
</SearchBar>
Use the component state to persist your value. This way it stays in sync as the user changes the value.
function showYourText(e) {
// Process
this.setState({ taskName : e.target.value })
}
<SearchBar>
<InputText
type="search"
placeholder="Search for tasks in the BOQ..."
value={ this.state.taskName }
onChange={(e) => showYourText(e)}
/>
</SearchBar>

can't edit input with prop value

I have a string , in certain places I need to insert input tags with values. Everything displays fine , but I can't delete or edit values in input. What is wrong with that input?
editModalText() {
let modalMessage="Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back"
return (
<div>
{modalMessage
.split("/")
.map((text, idx) =>
text.includes("#") ? this.replaceCharacter(idx, text) : text,
)}
</div>
)
}
replaceCharacter(idx, text) {
let formattedText = text.replace(/#/g, " ")
return (
<input
key={idx}
value={formattedText}
onChange={e => this.setState({input:e.target.value})}
/>
)
}
replace value={formattedText} with defaultValue={formattedText}
this way input will be editable. it will show default value on first render and as you type you'll store that value in your state.
you can read more about controlled and uncontrolled components in the docs
I think you need to bind the input value and the state together. I am not sure how you're currently calling replaceCharacter but I would do something like this :
replaceCharacter(idx) {
return (
<input
key={idx}
value={this.state.input.replace(/#/g, " ")}
onChange={e => this.setState({input:e.target.value})}
/>
)
}
This way when you update your state with the onChange event the value of the state will be populated in the input.

React Application. Submit button is only returning "type" and not the actual value submitted to it

I want this application to be able to add a new animal object but when i console.log to see the output of my handle submit function it returns the string "type". Ive narrowed down the bug to be in my map method that returns the animal type: value='type'>{type}
but im unsure what to replace here to get the desired output of whats submitted
handleSubmit(e) {
console.log(this.refs.type.value)
e.preventDefault()
}
render() {
let typeOptions = this.props.types.map(type => {
return (<option key={type} value='type'>{type}</option>)
})
return (
<div>
<h3>Add an Animal</h3>
<form onSubmit={this.handleSubmit.bind(this)}>
<div>
<label>Species</label><br />
<input type='text' ref='species' />
</div>
<div>
<label>Type</label><br />
<select ref="type" >
{typeOptions}
</select>
</div>
<input type='submit' value='submit' />
</form>
</div>
return (<option key={type} value='type'>{type}</option>)
^^ 1 ^^ 2 ^^ 3
What is this key attribute? It does not exist in HTML. Get rid of it
Look here. You have set the value to be the hard-coded string 'type'. Don't do that. Use a variable.
Here you've used a variable. Do the same thing for the value attribute.

Categories