I can’t get this code to work for my project?

I’m still new to coding and im working on a project and I can’t seem to get this to work. when clicked from home page its supposed to send you to a different page and give you a random fortune, but all I am getting is a blank page.

import React from "react";

{/* <h1 id="fortune-holder" class="fade-animation">What is your fortune?</h1> */}
<body>
<h1 id="cookie" class="fade-animation">What is your fortune?</h1>
</body>


var fortunesArray = [
    "An exciting opporunity lies ahead",
    "A long time friend will brirng wise advice in the coming week",
    "You will find great fortunes in unexpected places",
    "Never give up... Unless you want to thats cool too",
    "111",
    "222",
    "333",
    "444",
    "Maybe a nap is what you need",
    "Don't Text Your EX!"

];



function getFortune() {
    var randomFortune = fortunesArray [
        Math.floor(Math.random()*fortunesArray.length)
    ];

console.log(randomFortune);

var fortuneHolder = document.getElementById("cookie");

fortuneHolder.innerHTML = randomFortune;

fortuneHolder.classList.remove("fade-animation");

void fortuneHolder.offsetWidth;

fortuneHolder.classList.add("fade-animation");


}


Answer

Lots going on here:

You need to put your JSX (what looks like HTML) into a render function (if using React.Component) or into a ‘return’ if just using a functional component.

Take a look at how this is constructed:

import React from "react";

class Fortune extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        fortunes: [
            "An exciting opporunity lies ahead",
            "A long time friend will brirng wise advice in the coming week",
            "You will find great fortunes in unexpected places",
            "Never give up... Unless you want to thats cool too",
            "111",
            "222",
            "333",
            "444",
            "Maybe a nap is what you need",
            "Don't Text Your EX!"
        ],
        fortune: ""
    }
}

componentDidMount() {
    this.getFortune();
}

getFortune = () =>  {
    let rand = Math.floor(Math.random() * (this.state.fortunes.length) + 0)
    console.log(rand);
    this.setState({
        fortune: this.state.fortunes[rand]
    })
}

render() {
    return (
        <div>
            {/* <h1 id="fortune-holder" class="fade-animation">What is your fortune?</h1> */}
            <h1 id="cookie" className="fade-animation">What is your fortune?</h1>
            <h5>{this.state.fortune}</h5>
        </div>
    )
}
}

export default Fortune;

This is an example of a React Component – see how it contains the function “getFortune” within it. The componentDidMount is a special function with react which runs when the component is mounted. So this calls getFortune(), which then adjusts the state.

Once the state is set with the random fortune, the render() function returns the random fortune below your initial H1 tag.