Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactjs Onclick event ,sending value to parent

Tags:

reactjs

I'm fairly very new to ReactJS, JavaScript and whole coding thing.

I have made a list of array that is being passed on to child from parent component, now I want to make a onClick event that whenever user click on any of that list item.

The value (used as key id) is sent back to the parent, so the parent can send that key value to another child which will use conditional rendering based on that key to which component to render. I preferably don't want to use any other library like flux.

I am stuck as I can;t pass that value from child back to parent. There is some confusion about syntax I think or maybe my logic is not correct. I have only able to bind it to a function within the child class to check if the click is being registered.

class Parent extends React.Component {   
 render() {
var rows = [];
this.props.listlinkarray.forEach(function(linklist) {
 rows.push(<Child linklist={linklist} key={linklist.key} />);
 });
return (
 <div> 
 <h3> ListHead </h3>
 {rows}

 </div>

);
}}

class Child extends React.Component {
// was checking how the Onclick event works //
getComponent(data,event) {    
  console.log('li item clicked!');
  console.log(data);
  event.currentTarget.style.backgroundColor = '#ccc';
}  
render() {
return (
<div>
   <ul><li onClick={this.getComponent.bind(this,this.props.linklist.key)}>

</div>
   );
  }
 }

Array has this data

var ListNameAndLinks= [
{ name:'ABC', key:1} ,
{ name:'BCD', key:2} 
 ];

I want to pass the value the parent get from child based on click to this class so it can render based on that value it get.

class Check extends React.Component {
 render() {
   var i = 1 
// i want that value from parent to this component in if condition
   if (i=1) { 
  return <UIone />;
}
 return <UItwo />;
 }
}
like image 564
Jheenga Avatar asked Jan 25 '17 12:01

Jheenga


1 Answers

Pass a onClick method from parent component, like this:

this.props.listlinkarray.forEach((linklist)=>{
    rows.push(<Child linklist={linklist} key={linklist.key} onClick={this.onClick.bind(this)}/>);
 });

Define this function in Parent:

onClick(key){
    console.log(key);
}

In Child Component call this method and pass the id back to parent, like this:

getComponent(key) {
   this.props.onClick(key);
}

It will work.

Check the jsfiddle for working example: https://jsfiddle.net/ahdqq5yy/

like image 199
Mayank Shukla Avatar answered Oct 09 '22 11:10

Mayank Shukla