'React onClick function on button is not working

I'm trying to build a simple webpage using React and Express. The page consists of a button and a number which should get incremented on clicking the button. I have used the number state to keep track of the value to be displayed and passed the component to my ejs file. Here are the codes for reference.

The react component test.jsx

import React from "react"

export default function Test(){
    const [number, setNumber] = React.useState(0);

    function add(){
        console.log(number)
        setNumber(number => number+1)
    }
    
    return(
        <div>
            <button onClick={add}>Click Me</button>
            <p>{number}</p>
        </div>
    )
}

I'm then passing this component to my ejs file through my router file

test.js

import React from "react"
import express from "express"
import {renderToString} from "react-dom/server.js"
import Test from "./test.jsx"

const router = express.Router();

router.get('/test', (req, res, next) => {
    const reactComp = renderToString(<Test/>);
    res.render("./test", {reactApp: reactComp});
})

module.exports = router;

test.ejs

<!DOCTYPE html>
<html>
    <body>
    <div id="body"> <%- reactApp %> </div>
    </body>
</html>

The problem is that the page gets rendered but the button does not seem to be working. The add function never gets called since there are no logs. Has it got something to do with the fact that I'm rendering through an ejs file? How do I make this work?



Solution 1:[1]

Why dont you just use axios ? or build a client to make the requests

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kodamace