Dummy example of using a React
ref
This example is useless and to the end user seems functionally equivalent to react/hello.html.It does however serve as a good example of what react does that is useful: it provides a "clear" separation between state and render code (which becomes once again much less clear in React function components.
Notably, this example is insane because at:we are extracing state from some random HTML string rather than having a clean JavaScript variable containing that value.
<button onClick={() => {
elem.innerHTML = (parseInt(elem.innerHTML) + 1).toString()
In this case we managed to get away with it, but this is in general not easy/possible.
react/ref-click-counter.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ref click counter</title>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Main extends React.Component {
constructor(props) {
super(props)
console.log('Main.constructor')
this.counterElem = null
}
render() {
console.log('render')
return (
<div>
<button onClick={() => {
console.log('onClick')
elem = this.counterElem
elem.innerHTML = (parseInt(elem.innerHTML) + 1).toString()
}}>
Click me
</button>
<div
ref={
(elem) => {
console.log(`ref callback ${elem}`)
this.counterElem = elem
}
}
>
0
</div>
</div>
)
}
}
ReactDOM.render(
<Main/>,
document.getElementById('root')
)
</script>
</body>
</html>