How to sum, divide values of multiple inputs using onChange event | ReactJS - javascript

i try make my first App in react, everything works, but i try take amoun of bill and number of people and divide te bill for person, and add Tip. I know for somebody probably its 5 min solution but i start working with that yesterday and still can't find solution.
I wanna take bill amount and divide by personAmount + tip if somebody choose tip. What i do wrong
import React, { useState } from 'react'
import style from './BillSplitter.module.css'
const tips = [5, 10, 15, 25]
const Input = ({ label, id, handleChange, name, type, placeholder }) => (
<>
<label className={`${style.label}`} htmlFor={id}>{label}</label>
<input className={`${style.input}`} type={type || "number"} id={id} name={name || id} placeholder={placeholder} onChange={handleChange}></input>
<br />
</>
);
const SelectTip = ({ tip }) => {
<>
<button className='tipButton' value={tip}></button>
</>
}
function BillSplitter() {
const [tipAmount, setTipAmount] = useState(0)
const [billAmount, setBillAmount] = useState(0)
const [personAmount, setPersonAmount] = useState(0)
function handleChange(e) {
console.log(e.target.value)
}
return (
<div className={`${style.wrapper}`}>
<div className={`${style.box}`}>
<div className={`${style.top}`}>
<h2 className={`${style.title}`}>Bill Splitter</h2>
<p className={`${style.personBillAmount}`}>Person Bill Amount</p>
<p onChange={handleChange} className={`${style.totalPersonAmount}`} >$ {tipAmount}</p>
</div>
<div className={`${style.bottom}`}>
<Input handleChange={handleChange} className={`${style.clases}`} placeholder='Amount of bill' label="Bill value">{billAmount}</Input>
<Input handleChange={handleChange} className={`${style.clases}`} placeholder='Number of people' label="Number of people">{personAmount}</Input>
<div className={`${style.tipBox}`}>
<p>Select tip</p>
{tips.map((tip) => {
return <button className={`${style.tipButton}`}>{tip} %</button>
})}
</div>
</div>
</div>
</div>
)
}
export default BillSplitter

Added onChange handler to the Input component and pass the different input setter functions. Then do the calculation when the tip is selected.
Try like below:
const tips = [5, 10, 15, 25];
const Input = ({ label, id, handleChange, name, type, placeholder }) => (
<React.Fragment>
<label htmlFor={id}>{label}</label>
<input
type={type || "number"}
id={id}
name={name || id}
placeholder={placeholder}
onChange={(e) => handleChange(e.target.value)}
></input>
<br />
</React.Fragment>
);
function BillSplitter() {
const [billAmount, setBillAmount] = React.useState(0);
const [personAmount, setPersonAmount] = React.useState(0);
const [perCost, setPerCost] = React.useState(0);
const calculatePerPeronAmount = (tip) => {
if (personAmount > 0) {
setPerCost(((1 + 0.01 * tip) * billAmount) / personAmount);
}
};
return (
<div>
<div>
<div>
<h2>Bill Splitter</h2>
<p>Person Bill Amount</p>
<p>$ {perCost}</p>
</div>
<div>
<Input
handleChange={setBillAmount}
placeholder="Amount of bill"
label="Bill value"
>
{billAmount}
</Input>
<Input
handleChange={setPersonAmount}
placeholder="Number of people"
label="Number of people"
>
{personAmount}
</Input>
<div>
<p>Select tip</p>
{tips.map((tip) => {
return (
<button onClick={() => calculatePerPeronAmount(tip)} key={tip}>
{tip} %
</button>
);
})}
</div>
</div>
</div>
</div>
);
}
ReactDOM.render(<BillSplitter />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div class='react'></div>

Related

How to pre-populate fields on click of a button in react?

I am trying to pre-populate the form fields, that are replicated, from the fields that are already filled. On clicking the "Add fields" button, the fields are getting replicated. But I want them to get pre-populated using the data filled in the already existing fields.
From where can I get hold of the input values?
import './style.css';
export default function App() {
const [inputFields, setInputFields] = useState([{ name: '', age: '' }]);
const addFields = (e) => {
e.preventDefault();
let newField = { name: "", age: '' };
setInputFields([...inputFields, newField]);
};
const handleFormChange = (index, e) => {
let data=[...inputFields];
data[index][e.target.name]=[e.target.value];
setInputFields(data);
}
return (
<div>
<form>
{inputFields.map((input, index) => {
return (
<div key={index}>
<input
type="text"
name="name"
placeholder="Enter name"
value={input.name}
onChange={(e)=>handleFormChange(index, e)}
/>
<input
type="number"
name="age"
placeholder="Enter Age"
value={input.age}
onChange={(e)=>handleFormChange(index, e)}
/>
<br />
<br />
</div>
);
})}
<button onClick={addFields}>Add Field</button>
<br />
</form>
</div>
);
}```
You will need to track changes in input with an onChange handler.
Also, you are not setting values from the last input fields anywhere to be able to duplicate them. The below code might work as you expect:
const { useState } = React;
function App() {
const [inputFields, setInputFields] = useState([{ name: '', age: '' }]);
const addFields = (e) => {
e.preventDefault();
const temp = inputFields.slice()
, length = temp.length - 1
, { name, age } = temp[length]
// Set value from last input into the new field
let newField = { name, age }
setInputFields([...temp, newField])
}
, handleChange = (index, event) => {
const temp = inputFields.slice() // Make a copy of the input array first.
inputFields[index][event.target.name] = event.target.value // Update it with the modified values.
setInputFields(temp) // Update the state.
};
return (
<div>
<form>
{inputFields.map((input, index) => {
return (
<div key={index}>
<input
onChange={e => handleChange(index, e)}
value={input.name}
type="text"
name="name"
placeholder="Enter name"
/>
<input
onChange={e => handleChange(index, e)}
value={input.age}
type="number"
name="age"
placeholder="Enter Age"
/>
<br />
<br />
</div>
);
})}
<button onClick={addFields}>Add Field</button>
<br />
</form>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
You have to set the value property on the input field to populate, e.g:
<input
value={input.name}
type="text"
name="name"
placeholder="Enter name"
/>

saving data into array functional components

I have a react form whose data must be saved in an array (what i want) values from the form include 3 selectable values, and two input values ( a number input and textarea ) each time a user is done with entering data, they press save button to push that entered data ( converted to an object ) into the array. I expect that each time user clicks save button, they are saving different data from the previous, which is then again pushed into the same array as an object. the array has a fixed length and I expect to not accept anymore data if it reaches a certain length. this works very well each a user saves data in that array only when the values of the two input fields (number input and textarea) the challenge is that each time the user data from any of the 3 selectable (as long as a select field is touched, even if the selected value is the same as the preivous value) values, the array loses the previous data and saves the current as array[0], the select fields are customised components using react-select, I extract data selected using useState, and other input fields are customised components from regular html input fields, I extract data input, using useRef, and forwadRef.
Kindly help and suggest how I can go about this.
export const Input = forwardRef((props, ref) => {
return (
<input
min={1}
required={props.required}
type={props.type}
id={props.id}
name={props.name}
placeholder={props.placeholder}
autoComplete={props.autoComplete}
autoCapitalize="none"
autoCorrect='off'
onChange={props.onChange}
defaultValue={props.defaultValue}
ref={ref}
{...props}
/>
);
});
const MySelect = (props) => {
const MyTheme = (theme) => {
return {
...theme,
colors: {
...theme.colors,
primary25: "#bdbdbd",
color: "#000",
primary: "rgba(0, 0, 0, 0.3)",
},
};
};
return (
<div style={{ width: "80%" }}>
<Select
defaultValue={props.defaultValue}
menuPlacement="auto"
menuPosition="auto"
placeholder={props.placeholder}
value={props.value}
onChange={props.onChange}
options={props.options}
isSearchable
isDisabled={props.isDisabled}
theme={MyTheme}
name={props.name}
id={props.id}
// ref={props.ref}
required = {props.required}
/>
</div>
);
};
export default MySelect;
const TextReminder = (props) => {
const [kickStart, setKickStart] = useState("");
const TimerRef = useRef();
const [units, setUnits] = useState("");
const [tag, setTag] = useState("");
const tagRef = useRef()
const TextRef = useRef();
const maxW = props.maxW
const handleAdd = (e) => {
e.preventDefault();
};
const Reminders = []
const handleSave = (e) => {
e.preventDefault();
const TextInput = TextRef.current.value;
const TimeInput = TimerRef.current.value;
const KickStart = kickStart.value;
const Units = units.value;
const Tag = tag.value;
const Wmax = maxW.current.value
const Reminder = {
Message: TextInput,
Starter: KickStart,
SendTime: TimeInput,
TimeUnits: Units,
Id: Tag
};
if (Reminders.length !== parseInt(Wmax)) {
Reminders.push(Reminder);
console.log(Reminders);
} else {
console.log("can not save any more Reminders");
}
};
const Remove = (e) => {
e.preventDefault();
if (Reminders.length > 0) {
Reminders.pop();
console.log(Reminders);
} else {
alert("Sorry, your sms reminders basket is now empty");
console.log(Reminders);
}
};
const handleSubmit = (e) => {
e.preventDefault();
};
return (
<div>
<form onSubmit={handleSubmit}>
<div className={classes.email}>
<div className={classes.split}>
<div className={classes.left}>
<div className={classes.lefthead}>settings</div>
<div className={classes.selectors}>
<div className={classes.time}>
<div className={classes.heads}>
when{" "}
<span
className={classes.add}
title="Click to start editing your reminders. one at a time"
>
<FButton onClick={handleAdd}>add</FButton>
</span>
</div>
<MySelect
placeholder="Select Time ..."
options={Determinants}
onChange={setKickStart}
/>
</div>
<div className={classes.trigger}>
<div className={classes.heads}>select trigger</div>
<div className={classes.tips}>
<div className={classes.tip1}>
<Input type="number" defaultValue="5" ref={TimerRef} />
</div>
<div className={classes.tip2}>
<MySelect
placeholder="Units ..."
options={RideTriggers.before}
onChange={setUnits}
/>
</div>
</div>
</div>
<div className={classes.tags}>
<div className={classes.heads}>select tag</div>
<MySelect
placeholder="Select Tag ..."
options={Tags}
onChange={setTag}
ref={tagRef}
/>
</div>
</div>
</div>
<div className={classes.right}>
<div className={classes.label}>
<div className={classes.a}>
<label htmlFor="body">Body</label>
</div>
<div className={classes.b}>
<FButton>+ variables</FButton>
</div>
</div>
<div className={classes.textarea}>
<TextArea id="body" className={classes.text} ref={TextRef} />
</div>
<div className={classes.bb}>
<div
className={classes.bbf}
title="Remove the immediate previously saved reminder from your basket"
>
<FButton onClick={Remove}>remove</FButton>
</div>
<div
className={classes.bbf}
title="Add this reminder to your basket in the order of first-saved is first-sent and last-saved is last-sent"
>
<FButton onClick={handleSave}>save</FButton>
</div>
</div>
</div>
</div>
<footer>
<div className={classes.footerbtn}>
<div className={classes.close}>
<FButton type={"submit"}>done</FButton>
</div>
{/* <div className={classes.close}>
<FButton>cancel</FButton>
</div> */}
</div>
</footer>
</div>
</form>
</div>
);
};
export default TextReminder;

React js form validation not working as it should

I am trying to create a Form validation for 4 inputs, companyName - email - name - phone.
My aim is to validate them using regular expression and won't allow the user to press submit unless the inputs aregood to go.
Problem :
I set the logic testing just two validations so far, the company name and the email.
When I press sometimes submit, it ignores the validation and sometimes not.
Please help me to let them work properly.
import { React, useState, useEffect } from "react";
/*
*****
*****
Import Showcase.scss -
*/
import "./Showcase.scss";
const Showacase = () => {
/*
*****
*****
Logic Goes Here
*/
//State Management
//Company State
const [company, setCompany] = useState();
const [companyValue, setCompanyValue] = useState();
//name State
const [name, setName] = useState();
const [nameValue, setNameValue] = useState();
//Phone State
const [phone, setPhone] = useState();
const [phoneValue, setPhoneValue] = useState();
//Email State
const [email, setEmail] = useState();
const [emailValue, setEmailValue] = useState();
//Hide Inputs
const [input, setInput] = useState(true);
// Message State
const [message, setMessage] = useState(true);
// SubMessage
const [subMessage, setSubMessage] = useState(true);
//InsertLine
const [line, setLine] = useState(false);
//Hide Button
const [btn, setBtn] = useState(true);
/* Validation State */
const [emailValidate, setEmailValidate] = useState(false);
/* Validation State */
const [companyValidate, setCompanyValidate] = useState(false);
// OnSubmit
const onSubmit = (e) => {
e.preventDefault();
};
//onChange Company
const onChangeCompany = (e) => {
setCompany(e.target.value);
};
//OnClick
const onClick = (e) => {
// Company and Name
const reCompanyName = /^[a-zA-Z]{2,12}$/;
// Email Address
const reEmail =
/^([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/;
if (!reCompanyName.test(company)) {
setCompanyValidate(true);
return;
}
if (!reEmail.test(email)) {
setEmailValidate(true);
return;
}
//upComing Phone
if (company === "" || phone === "" || email === "" || name === "") {
return;
} else {
/* setting the New Values */
setCompanyValue(company);
setNameValue(name);
setPhoneValue(phone);
setEmailValue(email);
/* Clearing the Inputs */
setCompany("");
setName("");
setPhone("");
setEmail("");
/* Logic of hidding Items */
setInput(false);
setMessage(false);
setSubMessage(false);
setLine(true);
setBtn(false);
/* Reset all options after submission after 5 seconds */
setTimeout(() => {
setInput(!false);
setMessage(!false);
setSubMessage(!false);
setLine(!true);
setBtn(!false);
}, 5000);
}
};
return (
<>
{/* Showcase Main */}
<div className="Showcase">
<div className="Container">
{/* Showcase Main / Applying the flex */}
<div className="Showcase__inside">
{/* Right Side / form and logic */}
<div className="Showcase__inside--left">
<div className="Showcase__inside--left--box">
{/* the Top Message */}
{message ? (
<h1>Find inbound call centers for your company</h1>
) : (
<h1>Thank you for your request!</h1>
)}
{/* the sub Message Message */}
{subMessage ? (
<p>
Use our AI and Big Data driven call center sourcing solution
</p>
) : (
<p className="paragraphAfterSubmission">
You’ve taken the first step. Our experts will get in touch
with you soon.
</p>
)}
{/* Inserting the Line */}
{line ? <hr></hr> : null}
<form onSubmit={onSubmit}>
{/* Company */}
<div className="Showcase__inside--left--box--form">
<label for="company">Company </label>
{input ? (
<div>
<input
required
value={company}
onChange={onChangeCompany}
type="text"
id="company"
placeholder="Company"
name="company"
/>
{companyValidate ? (
<div className="companyValidate">
<small>Please Provide a valid Company Name</small>
</div>
) : (
""
)}
</div>
) : (
<p>{companyValue}</p>
)}
</div>
{/* Name */}
<div className="Showcase__inside--left--box--form">
<label for="Name">Name </label>
{input ? (
<input
required
onChange={(e) => setName(e.target.value)}
value={name}
type="text"
id="Name"
placeholder="Full name"
name="Name"
/>
) : (
<p>{nameValue}</p>
)}
</div>
{/* Phone */}
<div className="Showcase__inside--left--box--form">
<label for="Phone">Phone </label>
{input ? (
<input
required
onChange={(e) => setPhone(e.target.value)}
value={phone}
type="text"
id="Phone"
placeholder="+49"
name="phone"
/>
) : (
<p>{phoneValue}</p>
)}
</div>
{/* Email */}
<div className="Showcase__inside--left--box--form">
<label for="Email">Email </label>
{input ? (
<div>
<input
required
onChange={(e) => setEmail(e.target.value)}
value={email}
type="email"
id="Email"
placeholder="name#mail.com"
name="email"
/>
{emailValidate ? (
<div className="EmailValidate">
<small>Please Provide a valid Email</small>
</div>
) : (
""
)}
</div>
) : (
<p>{emailValue}</p>
)}
</div>
{/* Submit */}
<div className="Showcase__inside--left--box--form">
<div className="Showcase__inside--left--box--form--submit">
{/* OnClick Method */}
{btn ? (
<button onClick={onClick} type="submit">
Get informed
</button>
) : null}
</div>
</div>
</form>
</div>
</div>
{/* Right SIDE %s */}
<div className="Showcase__inside--right">
<div>
<div>
<h1>Welcome to Europe’s largest call center database </h1>
</div>
<div className="Showcase__inside--right--per">
<div className="Showcase__inside--right--per--single">
<small>500+</small>
<h1>Tenders</h1>
</div>
<div className="Showcase__inside--right--per--single">
<small>200+</small>
<h1>Callcenter</h1>
</div>
<div className="Showcase__inside--right--per--single">
<small>375.000</small>
<h1>Agents available</h1>
</div>
<div className="Showcase__inside--right--per--single">
<small>85%</small>
<h1>Faster sourcing</h1>
</div>
</div>
</div>
</div>
{/* Right Ended %s */}
</div>
</div>
</div>
</>
);
};
export default Showacase;

How to write inside input after making it editable?

I Am populating values of my input field from JSON data what am getting from back-end, now there is an edit button on UI by on click on that button I am enabling my input field but not able to type inside as I am setting some value
I want to write inside the input once I have made them editable.
const { register, handleSubmit, errors } = useForm();
const [disabled, setdisabled] = useState(false);
const [editBtn, seteditBtn] = useState(true);
<form onSubmit={handleSubmit(onSubmit)}>
{editBtn === true && (
<div align="right">
<button
className="btn white_color_btn"
type="button"
onClick={edit}
>
Edit
</button>
</div>
)}
{editBtn === false && (
<button className="btn white_color_btn" type="submit">
Save
</button>
)}
<div className="row">
<div className="form-group col-6 col-sm-6 col-md-6 col-lg-4 col-xl-4">
<input
type="text"
disable
id="firstName"
name="firstName"
value={dataItems.firstname}
disabled={disabled ? "" : "disabled"}
ref={register({ required: true })}
/>
{errors.firstname && (
<span className="text-danger">first name required</span>
)}
<br />
<label htmlFor="emp_designation">First name</label>
</div>
<div className="form-group col-6 col-sm-6 col-md-6 col-lg-4 col-xl-4">
<input
type="text"
disabled
id="lastname"
name="lastname"
value={dataItems.lastname}
disabled={disabled ? "" : "disabled"}
ref={register({ required: true })}
/>
{errors.lastname && (
<span className="text-danger">last name required</span>
)}
<br />
<label htmlFor="lastname">Lastname</label>
</div>
</div>
</form>
On click of edit
const edit = () => {
setdisabled(true);
};
Code sandbox
You need to make your input as a controlled component and write onChange handlers which will update the state. This will allow you to edit the input field values. Demo
const [disabled, setdisabled] = useState(false);
const [name, setName] = useState(empData.item.name) // setting default name
const [lastname, setLastname] = useState(empData.item.lastname) // default lastname
const edit = () => {
setdisabled(true);
};
return (<div className="container-fluid">
<div align="right">
<button className="btn" onClick={edit}>
Edit
</button>
</div>
<div className="row">
<div>
<input
type="text"
disable
id="item.value"
value={name}
onChange={(e) => {
setName(e.target.value)
}}
disabled={disabled ? "" : "disabled"}
/>
<br />
<label htmlFor="name">Name</label>
</div>
<div>
<input
type="text"
disabled
id={"lastname"}
value={lastname}
onChange={(e) => {
setLastname(e.target.value)
}}
disabled={disabled ? "" : "disabled"}
/>
<br />
<label htmlFor="lastname">Lastname</label>
</div>
</div>
</div>);
Your input is controlled by the value you are giving to it. ie: Its value is always for example empData.item.name.
And you are not providing a change handler to handle the change.
Try adding something like this:
function myChangeHandler(e){
setEditedValueSomeHow(e.target.value);
}
<input
// ...
onChange={myChangeHandler}
/>
Read more about uncontrolled components
PS: you should have had a warning message in your console like this one:
Edit:
You are using react-hook-form to manage your form but at the same time giving values to your inputs.
Please refer to this link to initialize your form values.
short story:
Remove value form your input.
Pass an object to useForm hook containing initial values.
const { register, handleSubmit, errors } = useForm({
defaultValues: {
firstName: "steve",
lastname: "smith"
}
});
Here is a working fork for your codesandbox
In order to make the input editable, you need to update a local state which controlls the input value. As suggested by you in the comments, you are using graphql to get the data, you can make use of useEffect to set the data in state and then on click of edit, update the localState
export default function App() {
const { register, handleSubmit, errors } = useForm();
const [disabled, setdisabled] = useState(true);
const [editBtn, seteditBtn] = useState(true);
const { loading, data } = useQuery("some qraphql query here"); // getting data from graphql
const [formData, setFormData] = useState({});
useEffect(() => {
setFormData(data);
}, [data]);
const edit = () => {
setdisabled(false);
seteditBtn(false);
};
const onSubmit = () => {
console.log(formData);
// submit data using formData state.
};
const handleChange = e => {
const name = e.target.name;
const value = e.target.value;
console.log(name, value);
setFormData(prev => ({ ...prev, [name]: value }));
};
return (
<div className="container-fluid">
<form onSubmit={handleSubmit(onSubmit)}>
{editBtn === true && (
<div align="right">
<button
className="btn white_color_btn"
type="button"
onClick={edit}
>
Edit
</button>
</div>
)}
{editBtn === false && (
<button className="btn white_color_btn" type="submit">
Save
</button>
)}
<div className="row">
<div className="form-group col-6 col-sm-6 col-md-6 col-lg-4 col-xl-4">
<input
type="text"
id="firstname"
name="firstname"
onChange={handleChange}
value={formData.firstname}
disabled={disabled}
ref={register({ required: true })}
/>
{errors.firstname && (
<span className="text-danger">first name required</span>
)}
<br />
<label htmlFor="emp_designation">First name</label>
</div>
<div className="form-group col-6 col-sm-6 col-md-6 col-lg-4 col-xl-4">
<input
type="text"
id="lastname"
name="lastname"
value={formData.lastname}
onChange={handleChange}
disabled={disabled}
ref={register({ required: true })}
/>
{errors.lastname && (
<span className="text-danger">last name required</span>
)}
<br />
<label htmlFor="lastname">Lastname</label>
</div>
</div>
</form>
</div>
);
}
Working mock demo

Input box won't accept anything ReactJS

I have this code, but I can't make it work. The input lines simply won't accept anything. I tried searching all over the place to no avail, so i decided to finally ask the question.
P.S. I am new to react
class App extends React.Component {
state = { inputValue: [{item:'', name:''}] }
handleChange = e => {
const newValue = [...this.state.inputValue];
newValue[0][e.target.name] = e.target.value;
this.setState({inputValue: newValue});
}
render(){
return(
<div className='container jumbotron'>
<div className="row">
<div className="col">
<FirstInput handleChange={this.handleChange} inputValue={this.state.inputValue[0].name}/>
</div>
<div className="col">
<SecondInput handleChange={this.handleChange} inputValue={this.state.inputValue[0].name}/>
</div>
</div>
</div>
);
}
}
const FirstInput = (props) => (
<div>
<label>First Input</label>
<input className="form-control" onChange={props.handleChange} value={props.inputValue}/>
</div>
)
const SecondInput = ({inputValue, handleChange}) => (
<div>
<label>Second Input</label>
<input className="form-control" onChange={handleChange} value={inputValue}/>
</div>
)
ReactDOM.render(<App />, document.getElementById('root'));
Sorry, I forgot to mention that I want to maintain the array as an array of object. The goal is to have first input and second input be the same value. Meaning, changing one input will make the other input the same.
You don't have name attribute defined on your Input elements and hence the value doesn't change. Update your code to
class App extends React.Component {
state = { inputValue: [{ item: '', name: '' }, { item: '', name: '' }] }
handleChange = e => {
const newValue = [...this.state.inputValue];
newValue[0][e.target.name] = e.target.value;
this.setState({ inputValue: newValue });
}
render() {
return (
<div className='container jumbotron'>
<div className="row">
<div className="col">
<FirstInput handleChange={this.handleChange} inputValue={this.state.inputValue[0].name} />
</div>
<div className="col">
<SecondInput handleChange={this.handleChange} inputValue={this.state.inputValue[0].item} />
</div>
</div>
</div>
);
}
}
const FirstInput = (props) => (
<div>
<label>First Input</label>
<input className="form-control" name="name" onChange={props.handleChange} value={props.inputValue} />
</div>
)
const SecondInput = ({ inputValue, handleChange }) => (
<div>
<label>Second Input</label>
<input className="form-control" name="item" onChange={handleChange} value={inputValue} />
</div>
)
You are overwriting your state. inputValue: [{item:'', name:''}] is an array, and handleChange you try to assign string value.
Your code should look like this one:
class App extends React.Component {
state = {
firstInput: '',
secondInput: ''
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value;
});
}
render(){
return(
<div className='container jumbotron'>
<div className="row">
<div className="col">
<Input
label="First Input"
name="firstInput"
handleChange={this.handleChange}
inputValue={firstInput}/>
</div>
<div className="col">
<Input
label="First Input"
name="secondInput"
handleChange={this.handleChange}
inputValue={secondInput}/>
</div>
</div>
</div>
);
}
}
const Input = (props) => (
<div>
{props.label && <label>{props.label}</label>}
<input
className="form-control"
onChange={props.handleChange}
name={props.name}
value={props.inputValue}/>
</div>
)
ReactDOM.render(<App />, document.getElementById('root'));

Categories