React – throw error when creating react component conditionally

I have a react component called ListChats and another called Chat.

ListChats calls the rendering of a Chat

I need that if an error occurs when rendering the Chat, ListChats knows and comes back with the list of available chats.

A possible error, its capture has not yet been implemented, would be if the user has no name, Chat captures this error and returns to ListChat.

ListChats component:

import React, { Component } from "react";
import Chat from "../Chat";
import { Button } from 'react-bootstrap';

export default class ListChats extends Component {

  constructor(props) {
    this.state = {
      chat: <div />
    this.toSala = this.toSala.bind(this);
  toSala() {
    //this is where I render a Chat component, I need that, if it returns an error, I set to "<div />" 
    this.setState({chat: <Chat/>  });
  render() {
    const { chat} = this.state;
    return (
         <Button  onClick={this.toSala}>abrir chat</Button>


Chat component

import React,{ useState, useEffect } from 'react'

const Chat = (props) => {
  const [name, setName] = useState('');
  const [room, setRoom] = useState('');
  const [users, setUsers] = useState([]);

useEffect(() => {    
 //depending on the value of a variable of mine I have the need or not to throw an error when rendering this component 
  }, []);

  return (
      my chat

export default Chat;

In short, I need to throw an error in the Chat component and catch it in ListChats component

1 thought on “React – throw error when creating react component conditionally”

Leave a Comment