Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access a property of a component in React from another file

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading