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

73
Visualizações
What is the best pattern for dynamically rendering components?

"Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it."

I have a simple Home component that I want to dynamically render components within based on if the user is logged in. However, I am getting the above warning from my return call, and it is making me wonder what other pattern I should be following. How would you improve this?

import React from 'react';
import Registration from './auth/Registration'
import Login from './auth/Login'
import Button from 'react-bootstrap/Button';
import { useNavigate } from 'react-router-dom'
import axios from "axios";



const Home = props => {

  const navigate = useNavigate();

  const handleSuccessfulAuth = (data) => {
    props.handleLogin(data);
    navigate('/dashboard');
  }

  const handleLogoutClick = () => {
    axios
      .delete("http://localhost:3001/logout", { withCredentials: true })
      .then(response => {
        props.handleLogout();
      })
      .catch(error => {
        console.log("logout error", error);
      });
  }

  const loginComponent = () => {
    return(
      <Login handleSuccessfulAuth={handleSuccessfulAuth} />
    )
  }

  const reRouteToDash = () => {
    navigate('/dashboard');
  }

  return (
    <div>
      <h1>Status: {props.isLoggedIn}</h1>
      <Button onClick={() => handleLogoutClick()}>Logout</Button>
      { props.isLoggedIn ? reRouteToDash : loginComponent }
    </div>
  );
}

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

0

You are almost there, the problem is that you are sending the function definition and you have to call it. Change the line to this:

  { props.isLoggedIn ? reRouteToDash() : loginComponent() }

And that should solve it.

You could also call only one function like this:

{ renderComponent() }

And have this in the function:

const renderComponent = () => {
 if (props.isLoggedIn) return navigate('/dashboard')
 return <Login handleSuccessfulAuth={handleSuccessfulAuth} />
}
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