Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type '{ name: string; }' is not assignable to type 'ReactNode'

I want to render names that are in the State. But I get this error: Type '{ name: string; }' is not assignable to type 'ReactNode'. I understand that ReactNode can't be assigned to an object, but is there any alternative to ReactNode, or what is the best practice?

Thank you in advance, it is my fist time doing something in React and TypeScript

Here is my code:

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { ReactNode } from "react";

interface State {
  monster1: {
    name: string;
  };
  monster2: {
    name: string;
  };
  monster3: {
    name: string;
  };
}

interface Props {}

class App extends React.PureComponent<Props, State> {
  constructor(props: Props) {
    super(props);

    this.state = {
      monster1: {
        name: "Linda",
      },

      monster2: {
        name: "Frank",
      },

      monster3: {
        name: "Jacky",
      },
    };
  }

  override render(): JSX.Element {
    {
      return (
        <div className="App">
          <div>
            <h1>{this.state.monster1}</h1>
            <h1>{this.state.monster2}</h1>
            <h1>{this.state.monster3}</h1>
          </div>
        </div>
      );
    }
  }
}

export default App;
like image 580
Dovul Avatar asked Oct 16 '25 00:10

Dovul


2 Answers

this.state.monster1 is an object with a property name. React does not allow you to render objects. You should access the name property (which hold a renderable string) instead:

<h1>{this.state.monster1.name}</h1>
<h1>{this.state.monster2.name}</h1>
<h1>{this.state.monster3.name}</h1>
like image 180
Tobias S. Avatar answered Oct 18 '25 16:10

Tobias S.


You should simply be returning your JSX (not within an object). The reason that ur seeing this error output is because Typescript is essentially saying: "hey you told me that I should expect a JSX.Element to be returned, but you instead are returning something else (aka an object).

With all that said the solution to your issue is:

override render(): JSX.Element {
    return (
        <div className="App">
            <div>
                <h1>{this.state.monster1}</h1>
                <h1>{this.state.monster2}</h1>
                <h1>{this.state.monster3}</h1>
            </div>
        </div>
    );
}
like image 26
Darren Baldwin Avatar answered Oct 18 '25 16:10

Darren Baldwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!