The following React example is a simple to-do list.
The HTML code for the React Custom component is:
<div class="container">
<div id="example2"></div>
</div>
The CSS code for the React Custom component is:
input {
display: block;
}
The JavaScript code for the React Custom component is:
async function start() {
const scriptsToLoad = [
"https://unpkg.com/react@18/umd/react.development.js",
"https://unpkg.com/react-dom@18/umd/react-dom.development.js"
];
// Load each script sequentially, waiting for each to finish before continuing
for (let script of scriptsToLoad) {
await loadExternalScript(script);
}
initializeReactApp();
}
function initializeReactApp() {
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
text: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return React.createElement(
"div",
null,
React.createElement(
"h3",
null,
"To-do list"
),
React.createElement(TodoList, {
items: this.state.items
}),
React.createElement(
"form", {
onSubmit: this.handleSubmit
},
React.createElement(
"label", {
htmlFor: "new-todo"
},
"What needs to be done?"
),
React.createElement("input", {
id: "new-todo",
onChange: this.handleChange,
value: this.state.text
}),
React.createElement(
"button",
null,
"Add #",
this.state.items.length + 1
)
)
);
}
handleChange(e) {
this.setState({
text: e.target.value
});
}
handleSubmit(e) {
e.preventDefault();
if (this.state.text.length === 0) {
return;
}
const newItem = {
text: this.state.text,
id: Date.now()
};
this.setState(state => ({
items: state.items.concat(newItem),
text: ''
}));
}
}
class TodoList extends React.Component {
render() {
return React.createElement(
"ol",
null,
this.props.items.map(item => React.createElement(
"li", {
key: item.id
},
item.text
))
);
}
}
const root = ReactDOM.createRoot(
document.querySelector('#example2')
);
root.render(React.createElement(TodoApp, null));
}
start();