Answer the question
In order to leave comments, you need to log in
How to call the method of another component from one component in React?
There is a list component:
class Service extends React.Component {
render() {
return (
<li className="services__item" onClick={Modal.openModal}>
{this.props.name}
</li>
);
}
}
class Modal extends React.Component{
constructor(props){
this.state = {
showModal: false
}
}
openModal = () =>{
this.setState = {showModal: true}
}
render(){
return(
<div>
<div className="service-modal-wrapper" openModal={this.openModal}>
<div className="service">
<div className="service-header">
<h3 className="service-header__title">{this.props.name}</h3>
</div>
<div className="service-content">
<ul className="service-content__descript">
<li className="service-content__item">1</li>
<li className="service-content__item">2</li>
<li className="service-content__item">3</li>
<li className="service-content__item">4</li>
</ul>
</div>
</div>
</div>
</div>
);
}
}
Answer the question
In order to leave comments, you need to log in
const Service = (props) => {
const [showModal, setShowModal] = useState(false)
return (
<div>
<li className="services__item" onClick={() =>setShowModal(true)}>
{props.name}
</li>
{showModal && <Modal />}
</div>
);
}
I can be wrong, but isn't this solved:
1. Either by passing the method to the props of the child component (in this case, the state of the modal window is stored in the parent component). The modal window is subscribed to the showModal state, and the Service component receives the method of changing the state of the modal window itself in props.
2. Since the components are class components, you can refer to native js and use the super () method ... but I'm not sure if this will be a good solution.
3. Or, as suggested by Zhanna_K, rewriting the styles of the component to absolute positioning.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question