ID photo of Ciro Santilli taken in 2013 right eyeCiro Santilli OurBigBook logoOurBigBook.com  Sponsor 中国独裁统治 China Dictatorship 新疆改造中心、六四事件、法轮功、郝海东、709大抓捕、2015巴拿马文件 邓家贵、低端人口、西藏骚乱
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:
<button onClick={() => {
  elem.innerHTML = (parseInt(elem.innerHTML) + 1).toString()
we are extracing state from some random HTML string rather than having a clean JavaScript variable containing that value.
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>

Ancestors (12)

  1. React DOM manipulation
  2. React
  3. List of front-end web frameworks
  4. Front-end web framework
  5. Web framework
  6. Web technology
  7. Software
  8. Computer
  9. Information technology
  10. Area of technology
  11. Technology
  12. Home