1

Sorry, React developer newbie. I am trying to use react-modal in my React Component based on the example here. I am getting a few errors I cannot figure out.

import React, {useState} from 'react';
import {
  Card, Button, CardImg, CardTitle, CardText, CardGroup,
  CardSubtitle, CardBody, CardFooter, CardHeader, CardColumns, CardDeck
} from 'reactstrap';
import Config from 'config';
import parse from 'html-react-parser';
import "./Item.css";
import ReactDOM from 'react-dom';
import Modal from 'react-modal';

const customStyles = {
    content: {
        top: '50%',
        left: '50%',
        right: 'auto',
        bottom: 'auto',
        marginRight: '-50%',
        transform: 'translate(-50%, -50%)',
    },
};

//Modal.setAppElement('FeaturedCards');

class FeaturedCards extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'React',
            apiData: [],
        };
    }

    async componentDidMount() {
        const tokenString = sessionStorage.getItem("token");
        const token = JSON.parse(tokenString);

        let headers = new Headers({
            "Accept": "application/json",
            "Content-Type": "application/json",
            'Authorization': 'Bearer ' + token.token
        });

        const response = await fetch(Config.apiUrl + `/api/Items/GetFeaturedItems`, {
            method: "GET",
            headers: headers
        });
        const json = await response.json();
        console.log(json);
        this.setState({ itemList: json });
    }

    render() {
        const [modalIsOpen, setIsOpen] = useState(false);
        const items = this.state.itemList;
        let subtitle;
        

        function handleClick(item) {
            console.log('this is:', item);
            setIsOpen(true);
        }

        function afterOpenModal() {
            // references are now sync'd and can be accessed.
            subtitle.style.color = '#f00';
        }

        function closeModal() {
            setIsOpen(false);
        }

        var formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD'            
        });

        return (
            <div>
                <CardColumns>
                    {items && items.map(item =>
                        <>
                            <Card key={item.itemNumber} tag="a" onClick={() => handleClick(item)} style={{ cursor: "pointer" }}>
                                <CardHeader tag="h3">Featured</CardHeader>
                                <CardImg top className="card-picture" src={"data:image/png;base64," + item.images[0]?.ImageData)} id={item.itemNumber + "Img"} alt={item.itemNumber} />
                                <CardBody className="card-body">
                                    <CardTitle tag="h5">{item.itemNumber}</CardTitle>
                                    <CardSubtitle tag="h6" className="mb-2 text-muted">{item.categoryName}</CardSubtitle>
                                    <CardText className="card-description">{item.itemDescription}</CardText>
                                </CardBody>
                                <CardFooter className="text-muted">{formatter.format(item.price)}</CardFooter>
                            </Card>
                            <Modal
                                isOpen={modalIsOpen}
                                onAfterOpen={afterOpenModal}
                                onRequestClose={closeModal}
                                style={customStyles}
                                contentLabel="Example Modal">
                                    <h2 ref={(_subtitle) => (subtitle = _subtitle)}>Hello</h2>
                                    <button onClick={closeModal}>close</button>
                                    <div>I am a modal</div>
                                    <form>
                                        <input />
                                        <button>tab navigation</button>
                                        <button>stays</button>
                                        <button>inside</button>
                                        <button>the modal</button>
                                    </form>
                            </Modal>
                        </>
                    )}                
                </CardColumns>
            </div>
        );
    }
}
export default FeaturedCards;

I am getting a number of errors:

  1. Where do I put const [modalIsOpen, setIsOpen] = useState(false) so I stop getting Error: Invalid hook call.?
  2. What do I need to put in Modal.setAppElement('FeaturedCards'), because FeaturedCards does not work?

Any help will be appreciated.

Randy
  • 1,137
  • 16
  • 49
  • 3
    The `useState` hook is how you use state in a function component. You're already using a _class_ component, so you shouldn't use hooks, just use regular state (`this.state.isOpen`). You already have some stateful things, this just becomes another piece of state. – Nick Jul 25 '21 at 13:19
  • 1
    Event handlers need to be bound to the component; this is searchable and in the React docs. – Dave Newton Jul 25 '21 at 14:53
  • @DaveNewton Hi, Dave. Thanks for the comment. Would you mind explaining a bit more. – Randy Jul 25 '21 at 15:05
  • 1
    Search for "react event handler binding" or something similar. That was my whole point--this is searchable, and (IMO anyway) that should be the first step (searching, I mean) once the search terms are known :) – Dave Newton Jul 25 '21 at 15:42

1 Answers1

0

After following @Nick and @DaveNewton comments...

...
Modal.setAppElement('#root');
...

class FeaturedCards extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'React',
            apiData: [],
            isOpen: false            
        };
    }

    ...    

    render() {
        const items = this.state.itemList;
        let subtitle;
        
        // This binding is necessary to make `this` work in the callback    
        handleClick = handleClick.bind(this);
        closeModal = closeModal.bind(this);

        function handleClick() {
            this.setState({ isOpen: true });
        }

        function closeModal() {
            console.log('Clicked close button')
            this.setState({ isOpen: false });
        }

        function afterOpenModal() {
            // references are now sync'd and can be accessed.
            subtitle.style.color = '#f00';
        }

        ...

        return (
            <div>
                <CardColumns>
                    {items && items.map(item =>
                        <>
                            <Card key={item.itemNumber} tag="a" onClick={() => handleClick()} style={{ cursor: "pointer" }}>
                                <CardHeader tag="h3">Featured</CardHeader>
                                <CardImg top className="card-picture" src={"data:image/png;base64," + item.images[0]?.ImageData} id={item.itemNumber + "Img"} alt={item.itemNumber} />
                                <CardBody className="card-body">
                                    <CardTitle tag="h5">{item.itemNumber}</CardTitle>
                                    <CardSubtitle tag="h6" className="mb-2 text-muted">{item.categoryName}</CardSubtitle>
                                    <CardText className="card-description">{item.itemDescription}</CardText>
                                </CardBody>
                                <CardFooter className="text-muted">{formatter.format(item.price)}</CardFooter>
                            </Card>
                            <Modal
                                isOpen={this.state.isOpen}
                                onAfterOpen={afterOpenModal}
                                onRequestClose={() => closeModal()}
                                style={customStyles}
                                contentLabel="Example Modal">
                                    <h2 ref={(_subtitle) => (subtitle = _subtitle)}>Hello</h2>
                                <button onClick={() => closeModal()}>close</button>
                                    <div>I am a modal</div>
                                    <form>
                                        <input />
                                        <button>tab navigation</button>
                                        <button>stays</button>
                                        <button>inside</button>
                                        <button>the modal</button>
                                    </form>
                            </Modal>
                        </>
                    )}                
                </CardColumns>
            </div>
        );
    }
}
export default FeaturedCards;

... I got the modal to open and close.

Randy
  • 1,137
  • 16
  • 49