简体   繁体   中英

Using React hooks for the first time and ran into an issue

I am using react for the first time in months and hooks for the first time ever. So far I love it, but I ran into an issue that has blocked me for hours now.

I have a component that looks like this:

import React, { useState } from "react";
import ReactModal from "react-modal";
import { useModal } from "react-modal-hook";
import styled from 'styled-components';

export function SearchImageForm(props) {

  const [query, setQuery] = useState("");
  const [images, setImages] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();

    fetch(`myurl&q=${query}`)
      .then((response) => {
        return response.json();
      })
      .then((myJson) => {
        if (myJson.totalHits > 0) {
          setImages(myJson.hits);
          showModal(images, handleClick);
        }
      });
  };

  const FormWrapper = styled.div`
    text-align: left;
  `;

  const Container = styled.div``;

  const LabelEl = styled.label``;

  const Input = styled.input``;

  const handleClick = (e) => {
    const urlField = document.querySelector('#url');
    urlField.value = e.target.src;
    urlField.select();
    document.execCommand("copy");
    alert('URL has been copied to your clipboard. You may now paste it into the URL field.')
  };

  return (
    <Container>
      <FormWrapper>
        <form onSubmit={handleSubmit}>
          <LabelEl>
            Enter Search Term
            <Input type="text" name="query" value={query} onChange={e => setQuery(e.target.value)} />
          </LabelEl>

          <input type="submit" value="Submit" />
        </form>
      </FormWrapper>
    </Container>
  );
}

export default SearchImageForm;

const ImageResult = ({content, handleClick}) => (
  <picture>
    <img src={content.previewURL} alt="" onClick={handleClick}/>
  </picture>
);


const [showModal, hideModal] = useModal(({images, handleClick}) => (<ReactModal isOpen ariaHideApp={false}>
  <p>Found {images.length} image(s). Click an image to copy its URL to your clipboard.</p>
  {images.map(image => <ImageResult key={image.id} content={image} handleClick={handleClick} />)}
  <input type="text" name="url" id="url" key="url" />
  <button onClick={hideModal}>Hide modal</button>
</ReactModal>));

When I try to run it, I get the React hooks error (Invalid Hook Call). Any ideas on what I am doing wrong here?

Here is the code on codesandbox, though i am not sure why it wont run. https://codesandbox.io/s/blue-firefly-0sx6h

Thanks!

The useModal hook needs to be called inside your component.

From the Invalid Hook Call Warning documentation:

Hooks can only be called inside the body of a function component.

So the modification what you need to do is the following:

export function SearchImageForm(props) {
   const [showModal, hideModal] = useModal(({images, handleClick}) => (
      <ReactModal isOpen ariaHideApp={false}>
         <p>Found {images.length} image(s). Click an image to copy its URL to your clipboard. </p>
         {images.map(image => <ImageResult key={image.id} content={image} handleClick={handleClick} />)}
         <input type="text" name="url" id="url" key="url" />
         <button onClick={hideModal}>Hide modal</button>
      </ReactModal>
   ));

   // ... rest of your component code

   return <>{/* your render */}</>
}

I hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM