Aakanksha Aakanksha - 3 months ago 8
React JSX Question

Call a React Component inside another component's function

I am trying React right now and i stumbled upon a idea. I wish to call a react component from the function of another react component. however, i cant get it to work. Below is my code,

var Snaker = React.createClass({
componentDidMount: function() {
$('.snacker').fadeIn(500);
$('.snacker').delay(2000).fadeOut(500);
},
render: function() {
return <div>
<div className="snacker snacker-right-top">
<p>{this.props.message}</p>
</div>
</div>
}
});

var Handle = React.createClass({
showSnaker: function(){
<Snaker message="React React"/>
},
render: function() {
return <div>
<Snaker message="React's example"/>
<a href="#" onClick={this.showSnaker}>Show me</a>
</div>
}
});

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


In the Handle component, i called the
Snaker
component and it works fine. However, what i want is the call the
Sanker
component when the link is clicked.I feel that this should do, however I cant get it to work. The JSFiddle to the same is here. Any help is appreciated. Thanks in advance. :)

Answer

try this https://jsfiddle.net/69z2wepo/55689/

var Snaker = React.createClass({
componentDidMount: function() {
    $('.snacker').fadeIn(500);
    $('.snacker').delay(2000).fadeOut(500);
  },
    render: function() {
    return <div>
              <div className="snacker snacker-right-top">
                <p>{this.props.message}</p>
              </div>
           </div>
    }
});

var Handle = React.createClass({
        getInitialState: function() {
    return {clicked: false};
  },

    showSnaker: function(){
        this.setState({clicked: true});
    },

        render: function() {
      return <div>
                {this.state.clicked ? <Snaker message="I am Rahul Gavande"/> : ""}
                <a href="#" onClick={this.showSnaker}>Show me</a>
             </div>
    }
});

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

for why it works, you are triggering the function showSnaker which in turn sets the clicked state to true. In react whenever a state changes it triggers a render and I have set the ternary operator check if the clicked state is true, to make the Snaker component visible and if not set, to show nothing {this.state.clicked ? <Snaker message="I am Rahul Gavande"/> : ""}