Reputation: 457
I am trying to call a method in a child component from a component that sits on the paerent component. Please see below:
App class
// App.js
class App extends Component {
render() {
return (
<div className="App">
<SimpleModal/>
<FloatingButton onClick={/*would like to call HandleOpen in SimpleModal*/}/>
</div>
);
}
}
export default App;
And here's that SimpleModal component
//SimpleModal
class SimpleModal extends React.Component {
state = {
open: false,
};
handleOpen = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
render() {
return (
<Modal
aria-labelledby="simple-modal-title"
aria-describedby="simple-modal-description"
open={this.state.open}
onClose={this.handleClose}
>
<div style={getModalStyle()}>
<Typography type="title" id="modal-title">
Text in a modal
</Typography>
<Typography type="subheading" id="simple-modal-description">
Description
</Typography>
</div>
</Modal>
);
}
}
export default SimpleModal;
Basically I would like to call HandleOpen and HandleCall from FloatingButton. How should I do this? Thank you in advance.
Upvotes: 0
Views: 34
Reputation: 42460
Instead of calling the functions from a sibling component, you could lift the state to the common parent component.
This allows you to pass the event handler into the FloatingButton
component, and the current state of the modal into the Modal
component.
For more infos, check out the relevant section in the React docs:
Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor.
Upvotes: 0
Reputation: 1432
Define both functions in the parent component (<App />
) and pass them to the child via props
. This way both <FloatingButton>
and <SimpleModal>
can have access to the same function. This technique is called "lift state up" and there is a very good article about it.
Upvotes: 1