Conditional returning error in Reactjs

Asked

Viewed 27 times

-1

My reactjs app only works if I remove the conditional. I figured it might be Babel’s fault, but if it was, JSX wouldn’t work even without parole.

App.js:

import React, {useState} from "react";

function App() {
  const [ versao, setVersao ] = useState(0);

  function alteraVersao() {
    setVersao(versao + 1)
  }

  return (
    
    {versao < 2 &&
      <div>
        <h1 className="titulo">Clicou {versao} vezes</h1>
        <button onClick={alteraVersao}>acrescenta cliques</button>
      </div>
    }
    
  )

}

export default App;

index js.:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(
  <App versao="2.0"/>,
  document.querySelector("#root")
)

Error: inserir a descrição da imagem aqui

  • return versao < 2 && ( /* ... */ ); 1) Remove the keys, since the versao < 2 is not inside JSX; 2) and place parentheses for JSX, since it occupies more than one line.

2 answers

0

Missing a parenthesis around the html

{versao < 2 && (
  <div>
    <h1 className="titulo">Clicou {versao} vezes</h1>
    <button onClick={alteraVersao}>acrescenta cliques</button>
  </div>
)}
  • It doesn’t work, keeps giving error in number 2

-1

Try that code:

export default App;

import React, { useState } from "react";

function App() {
  const [versao, setVersao] = useState(0);

  function alteraVersao() {
    setVersao(versao + 1);
  }

  return (
    { versao } < 3 && (
      <div>
        <h1 className="titulo">Clicou {versao} vezes</h1>
        <button onClick={alteraVersao}>acrescenta cliques</button>
      </div>
    )
  );
}

export default App;

`

Browser other questions tagged

You are not signed in. Login or sign up in order to post.