JS-JMS-WEB
JS-JMS-WEB

Reputation: 2625

react - click event on clild from parent

What is the best approach to achieve this:

I have a parent which renders a row:

< div className = "container" >         
 {this.state.rows.map(function(row, i) {
    return <ProjectsRow row={row} key={i} />
 }.bind(this))}
< /div> 

and child:

  return ( 
<ReactTransitionGroup transitionName="reactClass" transitionAppear={true}>  
    < div className = "row" > 
        {this.props.row.map(function(project) {
        return  < div className = "col-md-4 project" key={project.id} >
                < div className="text-center img-container"> <img alt="logo" src={project.thumbnail} />< /div >

                <h4 className="text-center"> 
                < a className = "linkStyle1"
                    href = {'#/project/' + project.id} >
                    <i className="fa fa-angle-right"></i>{project.title} 
                </a>
                < /h4>   

                < /div>
                    })}
                < /div> 
            <hr />  
            </ReactTransitionGroup> 

How can I have a onClick on h4 on child and access it in parent. I can only achieve this by jQuery which I shouldn't be doing.

Upvotes: 0

Views: 2940

Answers (2)

Michael Parker
Michael Parker

Reputation: 12966

var Parent = React.createClass({
  randomFunction : function () {
    alert('randomFunction() called in Parent');
  },
  render : function () {
    return (
      <div>
        <Child randomFunction={this.randomFunction} />
      </div>
    );
  }
});

var Child = React.createClass({
  render : function () {
    return (
      <div>
        <button onClick={this.props.randomFunction}>Click me to trigger function in Parent</button>
      </div>
    );
  }
});

Demo: http://jsbin.com/fibokeladi/edit?html,js,output

Upvotes: 1

Max Bumaye
Max Bumaye

Reputation: 1009

you can pass a callback down to you child

< div className = "container" >         
 {this.state.rows.map(function(row, i) {
    return <ProjectsRow row={row} key={i} onClickCb={this.onClickChild} />
 }.bind(this))}
< /div> 

onClickChild has to be defined in you parent component.

your Child component can attach this callback to its h4 evenhandler

< div className = "col-md-4 project" key={project.id} >
           < div className="text-center img-container"> <img alt="logo" src={project.thumbnail} />< /div >

        <h4 className="text-center" onClick={this.props.onClickCb}> 
        < a className = "linkStyle1"
            href = {'#/project/' + project.id} >
            <i className="fa fa-angle-right"></i>{project.title} 
        </a>
        < /h4>                                  
    < /div>

I hope this helped

Upvotes: 2

Related Questions