Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!