Answer the question
In order to leave comments, you need to log in
How to swap data in React components?
Goodnight. Please help. Give an example, if possible, how to change the data of the components.
For example, there are 2 inputs. City from where and city to. Each input has its own value, for example, Where is "Moscow", and where is "Peter". And there is a parent where both of these components exist.
How it is possible to change the data at the given components in places?
Answer the question
In order to leave comments, you need to log in
const Input = ({ label, ...props }) => (
<div>
<label>
{label}
<input {...props} />
</label>
</div>
);
class App extends React.Component {
state = {
from: 'Москва',
to: 'Питер',
}
onChange = ({ target: { value, name } }) => {
this.setState(() => ({
[name]: value,
}));
}
swap = () => {
this.setState(({ from, to }) => ({
from: to,
to: from,
}));
}
render() {
return (
<div>
<button onClick={this.swap}>swap</button>
<Input label="откуда" value={this.state.from} name="from" onChange={this.onChange} />
<Input label="куда" value={this.state.to} name="to" onChange={this.onChange} />
</div>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question