Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

247
Visualizações
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 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda