Answer the question
In order to leave comments, you need to log in
How to update state child-a from parent component, react?
Good afternoon! Please tell me how to update the state child from the parent in react if child is displayed in a loop?
Will he change in this case?
Component Example
export default class ParentBlock extends Component {
static propTypes = {
blocks: PropTypes.arrayOf(PropTypes.object),
};
render() {
const { blocks } = this.props;
return (
<ParentBlocksList blocks={blocks} />
)
}
}
const ParentBlocksList = ({
blocks,
}) => (
<div>
{blocks.map(block => (
<ParentBlockItem
key={block.id}
name={block.name}
values={block.values}
disabled={block.disabled || false}
/>
))}
</div>
);
const ParentBlockItem = ({
name,
values,
disabled,
}) => (
<div>
<table>
<tbody>
{Object.entries(values).map(([name, val]) => (
<ChildBlockItemRow
key={name}
name={name}
value={val}
disabled={disabled}
/>
))}
</tbody>
</table>
</div>
);
export default class Child extends Component {
static propTypes = {
name: PropTypes.string,
value: PropTypes.string,
disabled: PropTypes.bool,
};
state = {
value: this.props.value,
};
handleChange = (e) => {
const { value } = e.target;
this.setState({
value,
});
};
render() {
const { name, disabled } = this.props;
const { value } = this.state;
return (
<tr>
<td>{name}</td>
<td>
<input
type="text"
value={value}
onChange={this.handleChange}
disabled={disabled}
ref={(el) => {
this.input = el;
}}
/>
</td>
</tr>
);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question