user3470020
user3470020

Reputation:

how to pass argument in props using functional component

how to pass an argument in props using functional component, here I had given my worked example code, Let me explain, My click event will trigger from PopUpHandle when I click on the PopUpHandle I need to get the value from ContentSection component. ContentSection will be the listing, when clicking on each listing want to get the value of the current clicked list. I tried with this code my console printed undefined but I don't know how to handle with functional component.

class mainComponent extends Component {
    constructor(props) {
        super(props);
        this.popTrigger = this.popTrigger.bind(this);
    }

    popTrigger(data){
        console.log(data);
    }

    render(){
        return(
            <Popup popTrigger={this.popTrigger} />
        )
    }
}
export default mainComponent;

Popup component

const PopUpHandle = ({ popTrigger, value}) => <li onClick={popTrigger.bind(this, value)} />;

const ContentSection =({popTrigger, value}) =>(
    <div>
        {value === 'TEST1' && (
        <div>
            <PopUpHandle popTrigger={popTrigger} value={value} />
          </div>
        </div>
        )}
        {value === 'TEST2' && (
        <div>
            <PopUpHandle popTrigger={popTrigger} value={value} />
          </div>
        </div>
        )}
    </div>
)

const ContentList = (({ items, popTrigger}) => (
    <div>
      {items.map((value, index) => (
        <ContentSection
          key={`item-${index}`}
          popTrigger={popTrigger}
          index={index}
          value={value}
        />
      ))}
    </div>
  )
);

    class example extends Component {
    constructor(props) {
        super(props);
        this.state = {
          items: ['TEST1', 'TEST2', 'TEST3', 'TEST4'],
        };
        this.popTrigger = this.popTrigger.bind(this);
    }

    popTrigger(){
        this.props.popTrigger()
    }

    render(){
        return(
            <ContentList popTrigger={this.popTrigger} items={this.state.items} />
        )
    }
}
export default example;

Upvotes: 1

Views: 76

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281636

The ContentSection component is not passed a value prop and hence its not passed on to the PopUpHandle component. Pass it like

render(){
    return(
        <ContentSection popTrigger={this.popTrigger} value={"test1"} />
    )
}

Upvotes: 0

Anantha kumar
Anantha kumar

Reputation: 375

 popTrigger(data){
    console.log(data);
}

You didn't pass the data while calling this.props.popTrigger(). In javascript if you didn't pass the arguments, it will consider it as undefined.

Upvotes: 1

Related Questions