Goor Lavi
Goor Lavi

Reputation: 412

react-redux child1 trigger child2 container method

I am trying to triger child method by another child. by using their parent component.

i know when working with redux i need to change fields on the store and the the components is rerendering by the needed props. but in this case i dont need to save any thing, just to run the first child method each press.

import React from 'react';
import Child1Container from "./Child1Container";
import Child2Container from "./Child1Container";

export default class Parentextends React.Component {
  constructor(props){
    super(props);

  }

  RunChild1Method(){
    // Run Child1 Method 
  }

  render() {
    return (
            <div>
              <Child1Container />
              <Child2Container RunChild1Method={this.RunChild1Method} />
            <div> 
            )
  }
}

Chiled2 Container

import { connect } from 'react-redux';
import Child2Component from "./Child2Component";

const mapStateToProps = (state, ownProps) => {

    return {
          RunChild1Method: ownProps.RunChild1Method
    };
};

const Child2Container = connect(mapStateToProps)(Child2Component);

export default Child2Container ;

Child2 Component

import React from 'react';

export default class Child2Component extends React.Component {
  constructor(props){
    super(props);
  }

  render() {
    return (
      <button onclick={() => {this.props.RunChild1Method()}}> Click Me!</ button>

    )
  }
}

Upvotes: 0

Views: 9

Answers (1)

willwoo
willwoo

Reputation: 560

to achieve this use refs: https://reactjs.org/docs/refs-and-the-dom.html

export default class Parent extends React.Component {
  RunChild1Method(){
    if (!this.child1Ref) return;
    this.child1Ref.runMethod();
  }

  render() {
    return (
      <div>
        <Child1Container ref={(comp) => { this.child1Ref = comp; }} />
        <Child2Container RunChild1Method={this.RunChild1Method} />
      <div> 
    )
  }
}

However (My opinion) I would strongly recommend not structuring your apps like this. Components should be an encapsulation of functionality and this is an anti-pattern which will cause future headaches.

Upvotes: 1

Related Questions