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

100
Visualizações
Set local variable in method inside the html in reactjs

I have this method render, within which I am creating a local variable category. I need to set the value of this variable inside the html in return statement using JSX.

I am using curly brackets to assign the value to the local variable, but this is not working for me. eg {category='business'}

This is what I am doing currently

export default class App extends Component {
  render() {
    let category = 'about';
    return (
      <Router>
        <div>
          <NavBar/>
          <Switch>
            <Route path="/about">
            </Route>
            <Route path="/business">
              {category='business'}
            </Route>
            <Route path="/entertainment">
              {category='entertainment'}
            </Route>
            <Route path="/general">
              {category='general'}
            </Route>
            <Route path="/health">
              {category='health'}
            </Route>
            <Route path="/science">
              {category='science'}
            </Route>
            <Route path="/sports">
              {category='sports'}
            </Route>
          </Switch>
          <News pageSize={5} country="in" category={category}/>
        </div>
      </Router>
    )
  }
}

This one instead shows the category on screen.

Note : I know there are multiple ways in which I can achieve this but I wanted to know how to set local variable within my method

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. First of all, look into functional components.
  2. A Route component expects a component, not logic. Handle the actual variable change in that component or elsewhere via react-router's useLocation hook.

What you're attempting to do is to change the state of the variable. Cue React's useState and useEffect hooks (the component needs to be a functional component for hooks to work).

First import the hook:

import { useState } from 'react';

Then, in your case:

const [category, setCategory] = useState('about') // initial value

and when you need to update it:

setCategory('science') // new value
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