I'm trying to convert my components to TypeScript. What type can I specify for render, which returns HTML?
class Component extends React.Component {
render() {
return (
<div>
...some HTML...
</div>
);
}
}
More on TypeScript. Render props is, according to the offical docs, a technique for sharing code between React components using a prop whose value is a function. The idea is to make components composable but being flexible in what to share.
React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.
Below are the list of following types used and return from render method, React elements: Elements that instruct React to render a DOM node. It includes html elements such as <div/> and user defined elements. Arrays and fragments: Return multiple elements to render as Arrays and Fragments to wrap multiple elements.
1. render() 101. First of all, render() is not user callable. It is part of the React component lifecycle. Generally, it gets called by React at various app stages when the React component instantiates for the first time, or when there is a new update to the component state.
I don't know whether it did when this question was first asked, but React has types available via the @types/react
module (now). The return type of render
is React.ReactNode
which is defined like this:
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
You can find the details of those various subtypes in the index.d.ts
file at DefinitelyTyped/DefinitelyTyped
.
Can I specify any type for render, which returns HTML?
render
doesn't return HTML (which would be a string). From the documentation:
When called, it should examine this.props and this.state and return one of the following types:
- React elements. Typically created via JSX. For example,
<div />
and<MyComponent />
are React elements that instruct React to render a DOM node, or another user-defined component, respectively.- Arrays and fragments. Let you return multiple elements from render. See the documentation on fragments for more details.
- Portals. Let you render children into a different DOM subtree. See the documentation on portals for more details.
- String and numbers. These are rendered as text nodes in the DOM.
- Booleans or null. Render nothing. (Mostly exists to support
return test && <Child />
pattern, where test is boolean.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With