I'm using the ES6 classes API of React (by using TypeScript) and want to render a subtyped class of type React.Component
using ReactDOM.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 the MyCustomProps
object.
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>