Home > database >  How can I trigger a child component function only for some specific parents component in next js?
How can I trigger a child component function only for some specific parents component in next js?

Time:11-28

I had a component say child.jsx and it has a button in it which triggers a function (named: handleClick) defined in the same component on clicking the button.

Now I imported this in two components say parent1.jsx and parent2.jsx.

What I want now is to call the handleClick function only when the button is clicked under parent1.jsx component and not in parent2.jsx.

Anyone can help with efficient solution to it ?

CodePudding user response:

You can pass a props like EnabledButton from parent1.jsx and check that into your click handler function

This is your Child Component

import React, { useState } from "react";

function Child(props) {

  function onclickHandler(event) {
    if(props.EnableButton)
    {    
      console.log(event.target.value);
    }
  }

  return (
    <div>
      <input
        type="button"
        value="Click Here"
        name="button"
        onClick={onclickHandler}
      />
    </div>
  );
}

export default Child;

How you pass props from parent1.jsx into your Child Component

<Child EnableButton ={true}>

How you pass props from parent2.jsx into your Child Component

<Child EnableButton ={false}>

Using this concept you can hide that button too.

  • Related