68 lines
2.5 KiB
Plaintext
68 lines
2.5 KiB
Plaintext
|
|
27-April-2021
|
||
|
|
|
||
|
|
- Summary: we can allow customers to create a custom-built component to replace a built-in component and run on our app.
|
||
|
|
|
||
|
|
- Steps:
|
||
|
|
+ Step 1: develop component as a normal react component in an react app. Make sure it is bug-free. Example
|
||
|
|
const TestComponent = () => {
|
||
|
|
const [counter, setCounter] = useState<number>(0);
|
||
|
|
const handleClick = () => {
|
||
|
|
alert('hello there');
|
||
|
|
}
|
||
|
|
|
||
|
|
return (
|
||
|
|
<div>
|
||
|
|
<h2>Counter: {counter} <span onClick={() => setCounter(counter + 1)}>[+]</span></h2>
|
||
|
|
<div>Click vào đây để thử nhé <span style={{color: 'green'}} onClick={handleClick}>Click</span></div>
|
||
|
|
</div>
|
||
|
|
)
|
||
|
|
}
|
||
|
|
|
||
|
|
+ Step 2: use https://babeljs.io/repl to transpire into js. The above will produce:
|
||
|
|
var TestComponent = function Test() {
|
||
|
|
var _useState = React.useState(0),
|
||
|
|
counter = _useState[0],
|
||
|
|
setCounter = _useState[1];
|
||
|
|
|
||
|
|
var handleClick = function handleClick() {
|
||
|
|
alert('hello there');
|
||
|
|
};
|
||
|
|
|
||
|
|
return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("h2", null, "Counter: ", counter, " ", /*#__PURE__*/React.createElement("span", {
|
||
|
|
onClick: function onClick() {
|
||
|
|
return setCounter(counter + 1);
|
||
|
|
}
|
||
|
|
}, "[+]")), /*#__PURE__*/React.createElement("div", null, "Click v\xE0o \u0111\xE2y \u0111\u1EC3 th\u1EED nh\xE9 ", /*#__PURE__*/React.createElement("span", {
|
||
|
|
style: {
|
||
|
|
color: 'green'
|
||
|
|
},
|
||
|
|
onClick: handleClick
|
||
|
|
}, "Click")));
|
||
|
|
};
|
||
|
|
|
||
|
|
+ Step 3: Insert the js code in database to produce in our app's html files. Example:
|
||
|
|
<head>
|
||
|
|
<script>
|
||
|
|
window.TestComponent = ....{content like above}
|
||
|
|
</script>
|
||
|
|
</head>
|
||
|
|
<body>
|
||
|
|
|
||
|
|
<!--// This is our app's files. No one can change--->
|
||
|
|
<script src="/static/js/bundle.js"></script>
|
||
|
|
<script src="/static/js/vendors~main.chunk.js"></script>
|
||
|
|
|
||
|
|
|
||
|
|
+ Step 4: In our app, use the code like CustomComponent/index.tsx
|
||
|
|
The app will check if there is a custom component, it will run!
|
||
|
|
|
||
|
|
- Trouble Shooting:
|
||
|
|
+ Error: React is not defined
|
||
|
|
Cause: React is built in because of webpack and custom components only can access React from window.React. To make React exposed to Window, in our app we can expose it (for example in the app's entry file index.tst)
|
||
|
|
|
||
|
|
//src/index.tsx:
|
||
|
|
import React from 'react';
|
||
|
|
...
|
||
|
|
window.React = React; // export React for outside world
|
||
|
|
...other
|