I have a component which is a form that receives props.
When I save the form I want to tell the parent component to send me updated props.
Not sure how to do that... Please can somebody point me in the right direction?
CodePudding user response:
You're probably looking for a pattern similar to this:
function ChildComponent(props) {
const [text, setText] = useState(props.text)
const handleClick = () => {
const newText = 'New Value'
setText(newText);
// this is needed to stop errors if the prop wasn't set.
props.onTextUpdated ? props.onTextUpdated(newText) : null;
}
return (
<div>
{text}
<button onClick={handleClick}>Send Update</button>
</div>
)
}
function ParentComponent() {
const [text, setText] = useState('this is some initial text');
const handleUpdate = (newValue) => {
alert('We could setText here too if we wanted!');
alert(newValue)
}
return (
<ChildComponent onTextUpdated={handleUpdate} text={text} />
)
}
CodePudding user response:
Have you checked the documentation?
I think the documentation is clear on this. I'm not sure I understand you but I see that in the documentation, we have a simple example of what to ask
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Le nom a été soumis : ' this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Nom :
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Envoyer" />
</form>
);
}
}
CodePudding user response:
You need to pass to the child component some callback that he can call when needed.
for example
const ChildComponent = ({callBack, data}) => {
return <>
<h1>{data}</h1>
<button onClick={callBack}>Click me</button>
</>
}
const ParentComponent = props => {
const [number, setNumber] = useState(0)
return <ChildComponent data={number} callBack={() => {setNumber(n => n 1)}}
}