Is It Possible To Export React Component As Function In Non-react Project
Solution 1:
If you want to create a function that will render a react component in a nonreact project, you can do that, but it's going to need to make use of reactDom.render, since that's the only way to take a react component and render it to the dom.
React components do not modify the dom themselves. All they do is create the "virtual dom", which is a set of types and props that react-dom can then use to update the dom. For example, let's take the very simplest of components:
() => <div/>
After transpiling the jsx, this turns into:
() => React.createElement("div", null);
And if you were to run this function, the result is a plain javascript object that looks like this:
{
$$typeof:Symbol(react.element),
key:null,
props: {},
ref:null,
type:'div'
}
More complicated components will create more complicated objects, and in the case of class components they create it via their render method, but in all cases the result is just a plain object. The dom has not been updated in creating this object, and the component contains no logic for updating the dom. It's React-Dom's job to take that object and figure out how to update the dom.
Here's an example of how you might package up a function for use in a non-react application which renders a react component:
importReactfrom'react';
importReactDOM from'react-dom';
classMyComponentextendsReact.Component {
// etc
}
exportdefaultfunctionrenderMyComponent(element, name) {
ReactDOM.render(<MyComponentname={name}>, element);
}
/** somewhere else: **/
renderMyComponent(document.getElementById('main'), 'Jake');
Solution 2:
You can import another component and call it like this:
importSecondComponentfrom'./SecondComponent'exportdefaultclassAppextendsReact.Component {
render() {
return (
<SecondComponent />
) }
}
Post a Comment for "Is It Possible To Export React Component As Function In Non-react Project"