Home > Software design >  Trigger events upwards for custom components
Trigger events upwards for custom components

Time:07-15

I have a custom made component called CoolButton. If I involve the component in another component like below, I'd somehow like to trigger the onClick-event, just like if it was a normal button.

A second question (not as important), is if it's possible to access the Press Me-value which was passed down the the CoolButton-component, in the child/CoolButton-Component. I'd much rather want Press Me to be dislayed instead of I'm button

export default function Home() {
  [timesClicked, setTimesClicked] = useState(0)

  return (
      <div className="home">
          <h1>Click the button!</h1>
          <div>The CoolButton has been clicked {timesClicked} times!</div>
          <CoolButton onClick={() => setTimesClicked(timesClicked   1)}>Press Me</CoolButton>    
      </div>
  ); 
}

export default function CoolButton() {
  return (
      <div className="cool_button">
        <button>I'm button</button>
      </div>
  ); 
}

CodePudding user response:

You are passing onClick as a prop to CoolButton component. Unless you use that prop in your component, it would not make any difference. Regarding your second question, if you would like wrap your component around some content, you should provide children in the component. Something like this:

export default function Home() {
  [timesClicked, setTimesClicked] = useState(0)
  
  return (
    <div className="home">
      <h1>Click the button!</h1>
      <div>The CoolButton has been clicked {timesClicked} times!</div>
      <CoolButton onClick={() => setTimesClicked(timesClicked   1)}>Press Me</CoolButton>    
    </div>
  );
}

export default function CoolButton(props) {
  return (
    <div className="cool_button">
      <button onClick={props.onClick}>{props.children}</button>
    </div>
  ); 
}

CodePudding user response:

You should pass the state variables down to the button and call them on the onClick event of the <button>.
You can pass a custom title to the button as prop as well

export default function Home() {
    const [timesClicked, setTimesClicked] = useState(0);
    return (
      <div className='home'>
        <h1>Click the button!</h1>
        <div>The CoolButton has been clicked {timesClicked} times!</div>
        <CoolButton
          setTimesClicked={setTimesClicked}
          title='Press Me'
        />
      </div>
    );
  }
  
  export default function CoolButton({ title, setTimesClicked }) {
    return (
      <div className='cool_button'>
        <button onClick={() => setTimesClicked((oldTimes) => oldTimes   1)}>{title}</button>
      </div>
    );
  }  
  • Related