M
M
Maxim Kalinin2020-10-06 22:45:43
React
Maxim Kalinin, 2020-10-06 22:45:43

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>
    );
  }
}


I want to click on it, turn to another component, call its method and thereby make it visible (modal window).
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>
           
        );
    }
}


How can I achieve this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zhanna_K, 2020-10-06
@Zhanna_K

const Service =  (props) => {
const [showModal, setShowModal] = useState(false)
    return (
<div>
      <li className="services__item" onClick={() =>setShowModal(true)}>
        {props.name}
      </li>
    {showModal && <Modal />}
</div>
    );
}

8
8XL, 2020-10-07
@8XL

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 question

Ask a Question

731 491 924 answers to any question