Onjsdev

Share


React Counter App Without JSX, Babel, Parcel, and Webpack


By onjsdev

Nov 26th, 2023

React allows us to build user interfaces with ease, but did you know you can use it without JSX, Babel, Parcel, or Webpack? Let's explore the alternative approach to building React applications.

How To Implement It

React actually is a javascript library, you can include it to any application without using any tool.

For example, JSX is a syntax extension for JavaScript recommended by React. However, it's not mandatory. You can write React components using plain JavaScript react.createElement function.

Babel is a powerful tool for transpiling modern JavaScript code. But, we do not need it because we will not use modern Javascript such as JSX syntax.

Webpack or Parcel are popular bundlers, but you do not need them as well, you can you can include react to your HTML file using CDNs.

Here is the example.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React Without Webpack</title>
</head>
<body>

  <div id="root"></div>



  <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>
  
  // Code goes here..
    
  </script>

</body>
</html>

Then open a script tag and add your react code here. Here is the example of a counter app in react wihout using jsx, babel or any bundler.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React Without Webpack</title>
</head>
<body>

  <div id="root"></div>

  <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>
    // React Component
    function Counter() {
      const [count, setCount] = React.useState(0);

      const increment = () => {
        setCount(count + 1);
      };

      return React.createElement('div', null,
        React.createElement('h1', null, `Count: ${count}`),
        React.createElement('button', { onClick: increment }, 'Increment')
      );
    }

    // Render the component
    const element = React.createElement(Counter);
    ReactDOM.render(element, document.getElementById('root'));
  </script>

</body>
</html>

In this example, we've created a Counter component using the React.createElement function. The component maintains a count state and updates it when the "Increment" button is clicked. This example demonstrates how to create React components without JSX and without the need for build tools like Babel, Parcel, or Webpack.

Conclusion

In conclusion, React development doesn't always require JSX, Babel, Parcel, or Webpack. For small projects or understanding how react works, give it a try this approach.

Thank you for reading.