Why adding react’s useState to a component was throwing an error and how I fixed it

I had the following code in my button.jsx file:

export default function ReactButton({ customClass = [], onSelect, children, ...props }) {


  // Ensure customClass is always an array
  const classNames = ['react-button', 'test-class', ...customClass].join(' ');

  return (
    <button className={classNames} onClick={onSelect} {...props}>{children}</button>
  );
}

Things were working fine, until I attempted to add useState to the mix:

import { useState } from "react";

export default function ReactButton({ customClass = [], onSelect, children, ...props }) {
  const [isClicked, setIsClicked] = useState(false);

  function handleClick() {
    setIsClicked(!isClicked);
    if (onSelect) {
      onSelect();
    }
  }

  // Ensure customClass is always an array
  const classNames = ['react-button', 'test-class', ...customClass].join(' ');

  return (
    <button className={classNames} onClick={onSelect} {...props}>{children}</button>
  );
}
Doing so, I my component no longer rendered in the browser and I began receiving the following error in the console:


Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

As it turned out, since I was loading my react library from CDN to the browser, I did not have a way to import the local react library as an ES module import.

However, what I _did_ have access to was the React object loaded in the browser by the CDN library. Once I changed my code to call that object directly the error went away and my component rendered correctly:

export default function ReactButton({ customClass = [], onSelect, children, ...props }) {
  //use React.useState instead of import { useState } from 'react';
  //since we are loading the React from CDN in index.html
  const [isClicked, setIsClicked] = React.useState(false);


  function handleClick(cb) {
    setIsClicked(!isClicked);
    if (onSelect) {
      onSelect();
    }
  }



  // Ensure customClass is always an array
  const classNames = ['react-button', 'test-class', ...customClass].join(' ');

  return (
    <button className={classNames} onClick={handleClick} {...props}>{children}</button>
  );
}

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *