Home > OS >  What is the best pattern for dynamically rendering components?
What is the best pattern for dynamically rendering components?

Time:01-18

"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

CodePudding user response:

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} />
}
  •  Tags:  
  • Related