Component doesn't display

Viewed 68

I have a header.tsx file with:

import React from "react";

export const Header = (title:any) => {
    return (
        <div>
            <h1>{title}</h1>
        </div>
    )
};

Then my index.tsx contains:

import React from "react";
import ReactDOM from "react-dom";
import { Header } from "./header"

ReactDOM.render(<Header title={"abc"} />, document.getElementById("root"));

However, when I do npm run dev, the code will compile successfully, the localhost page is empty (blank). Instead I expected it to display "abc".

If I instead define Header in this fashion, it'll magically work:

export class Header extends React.Component<{ title: string }> {
    render() {
        return (
            <div>
                {this.props.title}
            </div>
        )
    }
};

So what's wrong with the way that Header was originally defined above?

4 Answers

You are passing in a string, so no need to wrap it in an object.

import { render } from "react-dom";
import ReactDOM from "react-dom";

import { Header } from "./App";

// const rootElement = document.getElementById("root");
// render(<App />, rootElement);

ReactDOM.render(<Header title="abc" />, document.getElementById("root"));

Also, props is an object. You can change your header code as below:

import React from "react";

export const Header = (props: { title: string }) => {
  return (
    <div>
      <h1>{props.title}</h1>
    </div>
  );
};

Sandbox

Also, recommend to use any as a last resort. You probably are not making best use of TS, if you use any. You know your data type so use string.

Because you are using props wrong way. Props of Header is an object. You can use destructure object to fix your issue:

export const Header = ({title} : {title: string}) => {}
export const Header = (props:any) => {
    return (
        <div>
            <h1>{props.title}</h1>
        </div>
    )
};
Related