How to render a React component (ES6 API) directly using ReactDOM?
You should ues React.createElement
.
React.createElement
takes a tag name or component, a properties object, and variable number of optional child arguments.
E.g.
class App extends React.Component {
render(){
return (
<div><h1>Welcome to React</h1></div>
);
}
}
Using jsx
it can be rendered like this
ReactDOM.render(<App />, document.getElementById('app'));
In another way(without jsx
)
ReactDOM.render(React.createElement(App, null), document.getElementById('app'));
A running example -
class App extends React.Component {
render(){
return (
<div><h1>Welcome to React</h1></div>
);
}
}
ReactDOM.render(React.createElement(App, null), document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app">
</div>
Dynalon
Updated on July 31, 2022Comments
-
Dynalon almost 2 years
I'm using the ES6 classes API of React (by using TypeScript) and want to render a subtyped class of type
React.Component
usingReactDOM.render()
.The following code works:
class MyComponentProps { someMember: string; } class MyComponent extends React.Component<MyComponentProps, {}> { constructor(initialProps: MyComponentProps) { super(initialProps); } } let rootNode = document.getElementById('root'); ReactDOM.render( <MyComponent someMember="abcdef" />, rootNode )
Now, given the explicit typing of the constructor in
react.d.ts
, I'd assume I can pass an instance of the MyCustomProps object that populates with initial properties (as done in the above code). But how to render the component then directly without JSX/TSX syntax?The following does NOT work:
ReactDOM.render(new MyComponent(new MyComponentProps()), rootNode);
I know I could just use the JSX syntax as a workaround, but as my
MyCustomProps
object is pretty large, I don't want to repeat every member of theMyCustomProps
object. -
Dynalon about 8 yearsThe last line of code in your answer is what I was looking for, thx!
-
Nate Glenn about 8 yearsFuture Googlers: you should change your code to look like this if you are getting
TypeError: this is undefined
at react.js:5045. -
Minh Nghĩa over 3 yearsSo I have to use
ReactDOM.render(React.createElement(), root)
instead ofReactDOM.render(<div></div>, root)
? Is there anything can be done that makes TypeScript allow JSX literal inReactDOM.render()