VersifiXion
VersifiXion

Reputation: 2282

Calling a function coming from props [React]

I have a component AlertError which displays a message coming from props and I want onClick on this message to call a function coming from props too,

This function called is different according to the parent components of AlertError,

I succeeded to display the message, but the function is not executed,

I show you a small recreated example to ask you what's wrong in this,

Component 1

function Component1() {
  function one() {
    console.log("one");
  }
  
  return <AlertError message="one" function={() => one()} />
}

Component 2

function Component2() {
  function two() {
    console.log("two");
  }
  
  return <AlertError message="two" function={() => two()} />
}

Component AlertError

function AlertError() {
  return <div onClick={props.function}>{props.message}</div>
}

Upvotes: 0

Views: 92

Answers (2)

Someone Special
Someone Special

Reputation: 13588

You forgot the props

function AlertError(props) {  //<--- props here
  return <div onClick={props.function}>{props.message}</div>
}

https://codesandbox.io/s/relaxed-monad-isuqf?file=/src/App.js

Upvotes: 2

Muhammad Bilal Bangash
Muhammad Bilal Bangash

Reputation: 1206

<div role='button' onClick={props.function}>{props.message}</div>

add div role as a button

Upvotes: 0

Related Questions