Dovul
Dovul

Reputation: 43

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;

Upvotes: 4

Views: 26052

Answers (3)

Tobias S.
Tobias S.

Reputation: 23845

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>

Upvotes: 3

Darren Baldwin
Darren Baldwin

Reputation: 31

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>
    );
}

Upvotes: 3

Aneesh
Aneesh

Reputation: 1715

Your render function should directly return the JSX you are trying to render:

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>
    );
}

Upvotes: 1

Related Questions