Search code examples
javascriptreactjsreact-propsreact-component

Why is my component is not rendering when I pass it props (react)?


I made my front component similar to a login page. When I try to pass the begin prop Front doesn't render for some reason. If I don't pass it any props then it renders fine. I'm not sure why this is happening. Any help would be appreciated!

export default function App() {
const [start, setStart] = React.useState(false);
function startGame() {
    setStart(prevStart => !prevStart);
}
return (
    <div>
        <Front begin={startGame()} />
    </div>
)

}

export default function Front(props) {
return (
    <div className="login">
        <h1>Quizzical</h1>
        <h3>Read the questions carefully!</h3>
        <button onClick={props.begin} className="startButton">Start Quiz</button>
        <div className="blob-1"></div>
        <div className="blob-2"></div>
    </div>
)

}


Solution

  • Pass the function like this:

    <Front begin={startGame} />

    Instead of this:

    <Front begin={startGame()} />

    Because startGame() will run the function on site and what it returns would be passed as props. This case it returns void (nothing) which is not expected by the component, thus the error occured.