Home > Software engineering >  How to access a property of a component in React from another file
How to access a property of a component in React from another file

Time:07-16

import Buttons from "./components/Buttons"


function Calculator() {

  function handleButtons(i) {
    return(
      <Buttons value={i} onClick={printNumber}/>
    )
  }

  function printNumber() {
    console.log("Hello");
  }


  return (
    <>
      <div>
        {handleButtons(1)}
        {handleButtons(2)}
        {handleButtons(3)}
      </div>
      <div>
        {handleButtons(4)}
        {handleButtons(5)}
        {handleButtons(6)}
      </div>
      <div>
        {handleButtons(7)}
        {handleButtons(8)}
        {handleButtons(9)}
      </div>
    </>
  )
}

export default Calculator 

I'm trying to print out the number that corresponds to the button that is being clicked. But I dont know how to access the properties(value) of Button component from this file.

Here is the other file

function Buttons(props) {
    
    return (
        <button onClick={props.onClick}>{props.value}</button>
    )
}

export default Buttons

Im new to react btw

CodePudding user response:

Change your code too,

import Buttons from "./components/Buttons"


function Calculator() {

  function printNumber(num) {
    console.log(num);
  }


  return (
    <>
      <div>
        <Button value={1} onClick={() => printNumber(1)}/>
        <Button value={2} onClick={() => printNumber(2)}/>
        <Button value={3} onClick={() => printNumber(3)}/>
      </div>
    </>
  )
}

export default Calculator 
  • Related