Adisak Chaiyakul
Adisak Chaiyakul

Reputation: 81

how to trigger react component from other component

I want to trigger react component from other component. What is the best way to do it? I don't want to create new flag on redux store like "shouldShowMenu". I thinking about static method in react but i not expert in react.

import Menu from './component/menu'
const clickfeed = () => {Menu.staticClickEvent()}
<Provider>
  <Menu>
  <Feed onClick={clickfeed}/>
</Provider>

can i use static method like this and should i use static method change the component state.

Upvotes: 1

Views: 1618

Answers (2)

Pranesh Ravi
Pranesh Ravi

Reputation: 19133

You don't need redux for this. You can use ref to do this. Hope it helps!

<script src="https://unpkg.com/[email protected]/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container"></div>
<script type="text/babel">
//component 1
  var Hello = React.createClass({
    func: function() {
      console.log('I\'m inside Hello component')
    },
    render: function() {
      return <div > Hello World< /div>;
    }
  });


//component 2
  var Hello2 = React.createClass({
    componentDidMount(){
    //calling the func() of component 1 from component 2 using ref
  	  this.refs.hello.func()
    },
    render: function() {
      return <Hello ref="hello"/>;
   }
  })


ReactDOM.render( < Hello2 / > ,
  document.getElementById('container')
);

</script>

Upvotes: 1

roshow
roshow

Reputation: 11

You should go ahead and create that shouldShowMenu flag in your redux store. Once you have components interacting that way, it's an application state. It seems excessive at first but once you start having a value that is shared across components, this will save you a lot of headaches!

Upvotes: 1

Related Questions