1

I just have a project that i'm using react+typescript, and i have a simple question, i know there are multiple forms that i can pass values of a component through a arrow function parameter, but, i just search a lot and i can't find how can i make that:

<Button value={'1'} onClick={(e => SomeFunction(e.target))}>some text</Button>

The code inside the function, is something like that:

const SomeFunction = (e) => {
    console.log(e)
  }

I just want to pass to the Function, the value of the properties value, that is equal to '1', can you guys, help me?

3
  • There's no code inside that function... It'll do nothing! Well, maybe it could throw an error.
    – Triby
    Commented May 22, 2020 at 21:27
  • Yes! Thanks @ggorlen. I'm using e.target.value, but, what come using that , don't have the value of the button.
    – Baptista
    Commented May 22, 2020 at 21:29
  • I just made a few changes in the question, but, the essential is in the question, I would just like to receive the value in my function, so that I can use it in the future.
    – Baptista
    Commented May 22, 2020 at 21:32

2 Answers 2

2

Do this instead pass in the value as an argument into the function

<Button onClick={SomeFunction(1)}>some text</Button>

For a dynamic value you can do

['name'].map(val => (
  <Button onClick={SomeFunction(val)}>some text</Button>
))

Then on the function declaration

Const SomeFunction = value => event => {
   console.log(value) // 1
}

3
  • Yes, o just made that change on my code, but, i'm wondering when i have to pass a dynamic value of a component to my function, how i do that?
    – Baptista
    Commented May 22, 2020 at 21:44
  • For a dynamic value pass in the value as an argument to the function like I did, It'll still work
    – Shegun
    Commented May 22, 2020 at 21:48
  • @AndreiBaptista I just updated the answer to use a dynamic value
    – Shegun
    Commented May 22, 2020 at 21:53
1

You can say:

First take out the value property for the Button and pass it to the onClick function "SomeFunction('1')"

<Button onClick={(e => SomeFunction('1'))}>some text</Button>
const SomeFunction = (value) => {
    console.log(value)
}
2
  • Yes, but, i'm very worried when i have to pass a dynamic value of a component to my function.
    – Baptista
    Commented May 22, 2020 at 21:51
  • if its an array of items, you could use the map method to pass every item dynamically to the button Commented May 22, 2020 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.