Handling multiple onChange callbacks in a React component - reactjs

This is how I'm currently handling the scenario with two input boxes. As a separate update method for each one. Can/should this be done with a single handleChange method instead?
https://codepen.io/r11na/pen/bZKOpj?editors=0011
class App extends React.Component {
constructor(props) {
super(props);
this.handleChange1 = this.handleChange1.bind(this);
this.handleChange2 = this.handleChange2.bind(this);
this.state = {
name1: '',
name2: ''
};
};
handleChange1(e) {
this.setState({
name1: e.target.value
});
};
handleChange2(e) {
this.setState({
name2: e.target.value
});
};
render() {
return (
<div class="row column">
<Label name={this.state.name1}/>
<Input onChange={this.handleChange1} />
<Label name={this.state.name2}/>
<Input onChange={this.handleChange2} />
</div>
);
};
}
const Label = props => (
<p {...props}>Hello: <span className="label-name">{props.name}</span></p>
);
const Input = props => (
<input placeholder="Enter your name" {...props} type="text" />
);
ReactDOM.render(<App />, document.getElementById('app'))

Can/should this be done with a single handleChange method instead?
You can simplify your code like so.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name1: '',
name2: ''
};
};
handleChange(e, name) {
this.setState({ [name]: e.target.value });
};
render() {
return (
<div class="row column">
<Label name={this.state.name1}/>
<Input onChange={ (e) => this.handleChange(e, 'name1') } />
<Label name={this.state.name2}/>
<Input onChange={ (e) => this.handleChange(e, 'name2') } />
</div>
);
};
}
Example
Thanks #Alik that mentioned about eslint rule jsx-no-bind,
A bind call or arrow function in a JSX prop will create a brand new
function on every single render. This is bad for performance, as it
will result in the garbage collector being invoked way more than is
necessary.
Following this rule you can change your code like
class App extends React.Component {
constructor(props) {
super(props);
this.onChange = {
name1: this.handleChange.bind(this, 'name1'),
name2: this.handleChange.bind(this, 'name2'),
}
this.state = {
name1: '',
name2: ''
};
};
handleChange(name, event) {
this.setState({ [name]: event.target.value });
};
render() {
return (
<div class="row column">
<Label name={this.state.name1}/>
<Input onChange={ this.onChange.name1 } />
<Label name={this.state.name2}/>
<Input onChange={ this.onChange.name2 } />
</div>
);
};
}
Example

Related

want to set value to an array key in react state

In the below code I have a state inside in emplist array with some keys and by onchange() event i want to set the value to emplist array keys. How can i set that values please help me :).
import React from 'react';
export default class Registrations extends React.Component{
constructor(props){
super(props);
this.state = {
EmployeeList:[
{ EmployeeId : '' },
{ EmployeeName :'' },
{ EmployeeSalary :'' },
{ EmployeeAddress : '' },
{ EmployeeDetails :false },
],
};
}
handleChange = (e) =>{
// some code actions//
}
render(){
var {EmployeeId,EmployeeName,EmployeeSalary,EmployeeAddress} = this.state;
return(
<div>
<form>
<input type="text" placeholder="Enter EmployeeId" onChange={this.handleChange}
value={EmployeeId} name='EmployeeId'/><br />
<input type="text" placeholder="Enter EmployeeName" onChange={this.handleChange}
value={EmployeeName} name='EmployeeName'/><br />
<input type="text" placeholder="Enter EmployeeSalary" onChange=
{this.handleChange} value={EmployeeSalary} name='EmployeeSalary'/><br />
<input type="text" placeholder="Enter EmployeeAddress" onChange=
{this.handleChange} value={EmployeeAddress} name='EmployeeAddress'/><br />
<button onClick={this.handleSubmit}>Submit</button>
</form>
</div>
);
}
}
Can you explain more about what you want to do.
In your code above, you type in the data for each piece of data inside a single employee object, so you state should has this shape:
this.state = {
Employee: {
EmployeeId: '',
EmployeeName: '',
EmployeeSalary: '',
EmployeeAddress: '',
EmployeeDetails: false
}
};
handleChange = (e) => {
this.setState({
Employee: {...this.state.Employee, [e.target.name]: e.target.value }
})
};
render() {
var {
EmployeeId,
EmployeeName,
EmployeeSalary,
EmployeeAddress,
} = this.state.Employee; // change the destructuring as well
}

Add data to the page without refreshing it in React

I've posted this question earlier, but probably not quite clearly formulated it. I have a chat. When I add message it goes to database but not updated on page. So I need it to be updated on page after adding a msg.
Parent component Forms
export default class Forms extends Component {
constructor() {
super()
this.state = {
messages: [],
}
this.sendMessage = this.sendMessage.bind(this);
}
componentDidMount(){
client1.getEntries({limit:300, order: 'sys.createdAt',
content_type:'nameTest'}).then(response => {
this.setState({messages: response.items});
}).catch(e => {
console.log(e);
});
}
sendMessage(data) {
client2.getSpace(client2.space)
.then((space) => space.getEnvironment('master'))
.then((environment) => environment.createEntry('nameTest', {
fields: {
chatName: {
'en-US': data.get('chatName')
... some data
}
}))
.then((entry) => entry.publish())
.catch(console.error)
}
render() {
return (
<div className="chat">
<div className="container-xl">
<MessageList messages={this.state.messages}/>
<SendMsg onSendMessage={this.sendMessage}/>
</div>
</div>
);
}
}
the child component SengMsg
export default class SendMsg extends Component {
constructor() {
super()
this.state = {
message:'',
userEmail:'ddd#gmail.com',
chatName:'ggg'
}
this.sendMessage = this.sendMessage.bind(this)
this.handleChange = this.handleChange.bind(this)
}
handleChange(e) {
this.setState({
message: e.target.value,
})
}
sendMessage(e) {
e.preventDefault();
const { onSendMessage } = this.props;
const form = e.target;
const data = new FormData(form);
// if send message handler was passed, invoke with form data
onSendMessage && onSendMessage(data);
this.setState({
message: ''
})
}
render() {
return (
<div className="send-message">
<Form className="send-msg" onSubmit={this.sendMessage}>
<FormGroup>
<Input type="hidden" name="userEmail" value={this.state.userEmail}/>
</FormGroup>
<FormGroup>
<Input type="hidden" name="chatName" value={this.state.chatName}/>
</FormGroup>
<FormGroup>
<Input
type="text"
name="text"
onChange={this.handleChange}
value={this.state.message}
placeholder="Write your message here"
required />
</FormGroup>
<FormGroup>
<Input type="hidden" name="dateCreated" value={moment().format()} onChange={this.handleChange}/>
</FormGroup>
</Form>
</div>
);
}
}

How to pass Child Component's form value to Parent Component

Is there a way to pass form data from child component to Parent component, where submit buttons have been kept in parent component.
NOTE: - I don't want to use ref for this as the ref would be waste of so much of memory and I might have 6-7 children in the parent.
I have created a similar situation to show what I am stuck on.
class FirstChildForm extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
render() {
return (
<div className="form">
<input type="text" placeholder="Enter your name..." />
<input type="password" placeholder="Enter password" />
</div>
)
}
}
class SecondChildForm extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
render() {
return (
<div className="form">
<input type="text" placeholder="Enter your name..." />
<input type="password" placeholder="Enter password" />
</div>
);
}
}
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
handleSubmit = () => {
}
render() {
return (
<div className="parent">
<FirstChildForm />
<SecondChildForm />
<button onClick={this.handleSubmit}> Submit</button>
</div>
)
}
}
Sure, the concept is called lifting the state up. Basically, your <App /> component would hold the data from both components. I'm going to simplify a bit, but you should understand what I'm doing.
FirstChildForm.js
<input type="text" name="username" onChange={e => props.updateData('user', e.target.value)}
SecondChildForm.js
<input type="password" name="password" onChange={e => props.updateData('pass', e.target.value)}
App.js
export default class App extends React.Component {
constructor() {
super();
this.state = {
user: '',
pass: '',
};
}
handleSubmit = () => {};
updateData = (target, value) => {
this.setState({ [target]: value });
};
render() {
return (
<div className="parent">
<FirstChildForm updateData={this.updateData} />
<SecondChildForm updateData={this.updateData} />
<button onClick={this.handleSubmit}> Submit</button>
</div>
);
}
}
The <App /> component is the source of truth. Please note:
By lifting the state up, <FirstChildForm /> and <SecondChildForm /> don't need to be class based components anymore, they can be functional components. If you want them to remain class based for whatever reason, change props.updateData to this.props.updateData, else it won't work.
The parent is where we define the function, the child is where we execute it, sending data to parent, basically!
by passing a function to the child component as props and passing the child component's state as parameter to the function
as i dont know what you exactly want to code inside but only to understand checkout
following example
parent:
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
data: []
}
}
handleSubmit = () => {
}
handleData = (newData) => {
this.setState({data: newData});
}
render(){
return (
<div className="parent">
<FirstChildForm / >
<SecondChildForm onSelectData={this.handleData}/>
<button onClick={this.handleSubmit}> Submit</button>
</div>
)
}
}
Child:
class SecondChildForm extends React.Component{
constructor(props){
super(props);
this.state = {
data:'hello'
}
}
handleDataChange: function () {
var newData = this.state.data
this.props.onSelectData(newData);
},
render(){
return (
<div className="form">
<input type="text" placeholder="Enter your name..." />
<input type="password" placeholder="Enter password" />
<button onclick={this.handleDataChange}>submit</button>
</div>
);
}
}
You will have to pass a function down to your children components. Your children will now be able to bind this function from their props to the given fields.
class FirstChildForm extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
render() {
return (
<div className="form">
<input type="text" placeholder="Enter your name..." onChange={this.props.dataChanged('name')}/>
<input type="password" placeholder="Enter password" onChange={this.props.dataChanged('password')}/>
</div>
)
}
}
class SecondChildForm extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
render() {
return (
<div className="form">
<input type="text" placeholder="Enter your name..." onChange={this.props.dataChanged('name')}/>
<input type="password" placeholder="Enter password" onChange={this.props.dataChanged('password')}/>
</div>
);
}
}
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
handleChange = form => field => ev => {
this.setState(prev => ({ [form]: { ...prev[form], [field]: ev.target.value } }))
}
The resulting state of your parent will have the following structure :
{
'firstForm': {
'name': '',
'password': ''
},
'secondForm': {
'name': '',
'password': ''
}
}

React, setting initial value to input element

I have a list of students on my page. When I click on some student, a form should appear with input element for all of student's properties. When form is submitted, student's properties should change. The problem is when I want to set initial value of input elements as a properties of a current selected student. The value of input elements is filled with properties of a current student, but when I try to type something in that input, it's value does not change.
Code of Parent component
class App extends Component {
constructor(props){
super(props);
this.state = {
students :listStudents(),
visible: false,
index: 0,
student: listStudents()[0]
};
this.onClick = this.onClick.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.onNewStudentSubmit = this.onNewStudentSubmit.bind(this);
}
onClick(index){
if(this.state.visible){
this.setState({
visible: false,
index: 0
});
}
else {
let student1 = this.state.students
.filter(s => s.index === index);
this.setState({
visible: true,
index: index,
student: student1[0]
});
}
}
onSubmit(student){
let list = this.state.students
.map(s => {
if(s.index === this.state.index)
return student;
return s;
});
this.setState({
students : list,
visible: false
});
}
render() {
return (
<div className="App">
<StudentsList students={this.state.students} onClick={this.onClick}/>
<EditStudentDetails student={this.state.student} visible={this.state.visible} onSubmit={this.onSubmit}/>
<CreateStudent onSubmit={this.onNewStudentSubmit}/>
</div>
);
}
}
export default App;
onClick function changes selected student and stores it in state.student.
onSubmit function is triggered when the student's editing form is submitted.
Render returns the list of all students and a editing component which can be visible or not. Below is code of my editing component.
import React from 'react';
class EditStudentDetails extends React.Component{
constructor(props){
super(props);
this.state = {
name: "",
surname: "",
index : "",
class : "",
visible: ""
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleNameChange = this.handleNameChange.bind(this);
this.handleSurnameChange = this.handleSurnameChange.bind(this);
this.handleClassChange = this.handleClassChange.bind(this);
this.handleIndexChange = this.handleIndexChange.bind(this);
}
handleSubmit(e){
const student = {
name: this.state.name,
surname: this.state.surname,
index : this.state.index,
class : this.state.class
};
this.props.onSubmit(student);
e.preventDefault();
}
handleNameChange(e){
const newName = e.target.value;
this.setState({
name: newName
});
}
handleSurnameChange(e){
const newName = e.target.value;
this.setState({
surname: newName
});
}
handleIndexChange(e){
const newIndex = e.target.value;
this.setState({
index: newIndex
});
}
handleClassChange(e){
const newClass = e.target.value;
this.setState({
class: newClass
});
}
render(){
const type = this.props.visible ? {display: 'block'} : {display: 'none'} ;
return(
<div style={type}>
<form className="form-group" onSubmit={this.handleSubmit}>
Име
<input className="Name" type="text" onChange={this.handleNameChange} value={this.props.student.name}/>
Презиме
<input className="Surname" type="text" onChange={this.handleSurnameChange} value={this.props.student.surname}/>
Индекс
<input className="Index" type="text" onChange={this.handleIndexChange} value={this.props.student.index}/>
Насока
<input className="Class" type="text" onChange={this.handleClassChange} value={this.props.student.class}/>
<input className="submit btn" type="submit" value="Промени"/>
</form>
</div>
);
}
}
export default EditStudentDetails;
I try to set initial value by setting each input's value to the appropriate prop. Then when something is changed in the input component state should update. But as I said, the value of each input does not change.
You are telling React to use the passed prop as the input value, and since the props are not changed, the value isn't either. Set the passed props to the component state and update the state when the input is changed.
If you want to shave of some bytes, you could also use a more general onChange method as in the example below, given you are able to set a name property on the input fields.
class EditStudentDetails extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
surname: "",
index: "",
class: "",
visible: "",
...this.props.student
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit(e) {
const student = {
name: this.state.name,
surname: this.state.surname,
index: this.state.index,
class: this.state.class
};
this.props.onSubmit(student);
e.preventDefault();
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
render() {
const type = this.props.visible ? { display: 'block' } : { display: 'none' };
return (
<div style={type}>
<form className="form-group" onSubmit={this.handleSubmit}>
Име
<input className="Name" name="name" type="text" onChange={this.handleChange} value={this.state.name} />
Презиме
<input className="Surname" name="surname" type="text" onChange={this.handleChange} value={this.state.surname} />
Индекс
<input className="Index" name="index" type="text" onChange={this.handleChange} value={this.state.index} />
Насока
<input className="Class" name="class" type="text" onChange={this.handleChange} value={this.state.class} />
<input className="submit btn" type="submit" value="Промени" />
</form>
</div>
);
}
}
The problem is here.
<input className="Name" type="text" onChange={this.handleNameChange} value={this.props.student.name}/>
The value of the input is this.props.student.name,but in the this.handleNameChange, you change this.state.name,so when you type something,you can't see the change in the input value.
I suppose you need something like this:
this.state = {
class: props.student.name
}
...
<input className="Name" type="text" onChange={this.handleNameChange} value={this.state.name}/>

More compact way to write onChange handler for form with many inputs that affect nested state properties?

What is a more compact and more easy way to write a handleChange function for multiple input than the following:
import React from "react";
function initialState() {
return ({
customer: {
name: '',
primaryContactPerson: {
name: '',
email: ''
}
}
})
}
export default class AddCustomerForm extends React.Component {
constructor(props) {
super(props);
this.state = initialState();
this.handleChange = this.handleChange.bind(this);
}
handleChange(event, field) {
console.log(event.target.name);
switch(event.target.name) {
case 'customer.name':
console.log(1);
this.setState({
this: {
customer: {
name: event.target.value
}
}
})
break;
case 'customer.primaryContactPerson.name':
console.log(2);
this.setState({
this: {
customer: {
primaryContactPerson: {
name: event.target.value
}
}
}
})
break;
case 'customer.primaryContactPerson.email':
this.setState({
this: {
customer: {
primaryContactPerson: {
email: event.target.value
}
}
}
})
break;
default:
break;
}
this.setState({[event.target.name]: event.target.value});
}
render() {
return (
<div className='section section--full-width'>
<h1>Add Customer</h1>
<form onSubmit={this.handleSubmit}>
<div className='form__row'>
<label>
Customer name
</label>
<input type="text" name="customer.name" value={this.state.customer.Name} onChange={this.handleChange} />
</div>
<div className='form__row'>
<label>
Contact person
</label>
<input type="text" name="customer.primaryContactPerson.name" value={this.state.customer.primaryContactPerson.name} onChange={this.handleChange} />
</div>
<div className='form__row'>
<label>
Contact details
</label>
<input type="text" name="customer.primaryContactPerson.email" value={this.state.customer.primaryContactPerson.email} onChange={this.handleChange} />
</div>
<div>
<input type="submit" value="Add" />
</div>
</form>
</div>
);
}
}
I have tried the following method that does not work for nested objects:
handleChange(event, field) {
this.SetState({event.targetname: event.target.value})
}
One dirty hack is using lodash _.set Link. This is not the recommended method only a workaround.
you can use
const tmp = this.state;
_.set(tmp, event.target.name, event.target.value);
this.setState({ customer: tmp.customer });
if you want to avoid direct state mutation you can also use
const tmp = _.cloneDeep(this.state)
this process will be slower.

Resources