samuel ng
samuel ng

Reputation: 5

How to call a const on another class on React?

So i am new to ReactJS (specifically i am using NextJS) , here we have two file index.js and welcome.js

In index.js i added as a component, and there is a const called hideWelcome to hide this component and do some actions, but I would like to call hideWelcome in a Button that is inside Welcome.

Here’s the code :

index.js

import Welcome from ‘./welcome’

export default function Home() {

const hideWelcome = () => {
// do sth here
};

return (<Welcome />)
}

welcome.js

export default function Welcome() {
return(
<Button onClick={call hideWelcome from index.js} />)
}

Upvotes: 0

Views: 1563

Answers (2)

edhi.uchiha
edhi.uchiha

Reputation: 364

You can send the hideWelcome as props and call it in Welcome component from props:

export default function Welcome({ hideWelcome }) {
  return (
    <Button onClick={hideWelcome} />)
}

export default function Home() {

  const hideWelcome = () => {
    console.log("Hide Welcome");
  };

  return (<Welcome hideWelcome={hideWelcome} />)
}

You can destructuring the props object like :

Welcome({ hideWelcome }) 

Or just calling props.hideWelcome


export default function Welcome(props) {
  return (
    <Button onClick={props.hideWelcome} />)
}

export default function Home() {

  const hideWelcome = () => {
    console.log("Hide Welcome");
  };

  return (<Welcome hideWelcome={hideWelcome} />)
}

Upvotes: 0

Nicholas Tower
Nicholas Tower

Reputation: 85012

Pass hideWelcome as a prop, and then use it inside Welcome

export default function Home() {
  const hideWelcome = () => {
    // do sth here
  };

  return (<Welcome hideWelcome={hideWelcome}/>)
}

export default function Welcome({ hideWelcome }) {
  return(
    <Button onClick={hideWelcome} />
  )
}

Upvotes: 1

Related Questions