Home > Software engineering >  How to pass state to jsx, render it and update when state changes?
How to pass state to jsx, render it and update when state changes?

Time:09-17

I'm new to React but I'm having a lot of fun with it. I wanted to add a Fun Facts-generator to the "About me" section of my portfolio, and I figured out how to make it work through the console, but I'm having no luck passing the generated fact to the return() part of my component.

I'd like to write out the content of the variable funFactoid on the page every time the user clicks the button, through a <p>-tag for example.

This is currently what my code looks like (I've removed parts irrelevant to my question):

function About(props) {

  function funFact() {

    function randomIntFromInterval(min, max) { 
      return Math.floor(Math.random() * (max - min   1)   min)
    }

    const randomNumber = randomIntFromInterval(0, 4);

    const factArray = ["A", "B", "C", "D", "E"];

    console.log(factArray[randomNumber]);
    let funFactoid = factArray[randomNumber];
  }

  return (
    <div>
      
      <button onClick={funFact}>Click me for a fun fact!</button>
      <p>{ funFactoid }</p>

    </div>
  )
}
 
export default About;

I'm sure it's a ridiculously easy fix, but I'm self taught so I I've probably just missed some important part that explains how to do this.

Thanks in advance for helping me out! This is the first time I've come across a coding problem I haven't been able to solve through Googling, so I'm super thankful for any help.

CodePudding user response:

The var let funFactoid is not in the same scope as your return function, other than that you should not use let, but the useState hook to set values you want to render:

function About(props) {

  const [funFactiod, setFunFactoid] = useState("")

  function funFact() {

    function randomIntFromInterval(min, max) { 
      return Math.floor(Math.random() * (max - min   1)   min)
    }

    const randomNumber = randomIntFromInterval(0, 4);

    const factArray = ["A", "B", "C", "D", "E"];

    console.log(factArray[randomNumber]);
    setFunFactoid(factArray[randomNumber]);
  }

  return (
    <div>
      
      <button onClick={funFact}>Click me for a fun fact!</button>
      <p>{ funFactoid }</p>

    </div>
  )
}
 
export default About;

CodePudding user response:

I had just one suggestion

function randomIntFromInterval(min, max) { 
  return Math.floor(Math.random() * (max - min   1)   min)
}

function funFact() {

const factArray = ["A", "B", "C", "D", "E"];

const lastIndex = factArray.length - 1

const randomNumber = randomIntFromInterval(0, lastIndex);

console.log(factArray[randomNumber]);
setFunfactoid(factArray[randomNumber]);
 
}

You can add a lastIndex variable to keep away errors so you can change the array without worrying about the max number.

  • Related