reactjsarrow-functionsparsing-error

Arrow function not being recognized react


import React, {
  useState
} from 'react';
import Modal from 'react-modal';
import './testmodal.css';


class Testmodal extends React.Component {
  render() {
    const [modalIsOpen, setModalIsOpen] = useState(false)
    return ( <
      div className = "Testmodal" >
      <
      div >
      <
      button onClick {
        () => setModalIsOpen(true)
      } > Edit Profile < /button> <
      /div> <
      Modal isOpen = {
        modalIsOpen
      } >
      <
      h2 > Modal Type < /h2> <
      p > Modal body < /p> <
      div >
      <
      button onClick = {
        () => setModalIsOpen(false)
      } > < /button> <
      /div> <
      /Modal> <
      /div>
    )
  }
}

export default Testmodal;

I'm trying to make a modal component that can be exported onto a website I'm creating but for some reason when I run the file on my local machine it's picking up an error at the arrow function.

Parsing error: Unexpected token, expected "..." with a red arrow pointing at my arrow function brackets


Solution

  • Welcome to StackOverflow!

    Your issue is in using React Class Component with hooks.

    Hooks are designed to be used with functional components (Take a look at the first example).

    Class Components incorporate usage of this.state, while functional components incorporate usage of useState, useX, useY (hooks) as you did.

    Take a look at this fixed code:

    import React, { useState } from 'react';
    import Modal from 'react-modal';
    import './testmodal.css';
    
    const Testmodal = () => {
      const [modalIsOpen, setModalIsOpen] = useState(false);
    
      return (
        <div className="Testmodal">
          <div>
            <button onClick={() => setModalIsOpen(true)}> Edit Profile </button>
          </div>
          <Modal isOpen={modalIsOpen}>
            <h2> Modal Type </h2> <p> Modal body </p>
            <div>
              <button onClick={() => setModalIsOpen(false)}> </button>
            </div>
          </Modal>
        </div>
      );
    };
    
    export default Testmodal;
    

    What I changed is migrate the component from Class Testmodal extends React.Component to const Testmodal = () => {...}

    That is called migrating from Class Component to Functional component.

    Once the component is functional, you can use hooks inside of it, but remember to only use it in the highest scope.