Home > other >  How to fetch dynamic modal content from Database Data in React
How to fetch dynamic modal content from Database Data in React

Time:07-16

I'm trying to fetch a dynamic modal from my Firebase database.

/* src/App.js */
import './App.css'
import { useState, useEffect } from 'react';
import { database } from './firebase';
import { ref, onValue } from "firebase/database";
import Modal from "react-modal";

function Home() {  
    //Read from Database
    const [getInfo, setInfo] = useState([]);
    useEffect(() =>{
      const dbRef = ref(database, 'id/');
       onValue(dbRef, (snapshot) => {
         const data = snapshot.val();           
           setInfo(data);
           getInfo.toString()           
         });
       }, []);        

  //Modal
  const [modalIsOpen, setIsOpen] = useState(false);
  
   /*Open Modal*/
   function openModal() {
    setIsOpen(true);
  }

  /*Close Modal*/
  function closeModal() {
    setIsOpen(false);
  }

  return (       
    <div className="grid-container">
      
      {getInfo.map((id, value) => <div className='grid-item' key={value.toString()} title={id.title} onClick={openModal} style={{ backgroundImage: 'url('   id.imgURL   ')', backgroundSize: "cover", backgroundRepeat: "no-repeat", backgroundPosition: "center", }}></div>)}      
        
      <Modal closeTimeoutMS={500} isOpen={modalIsOpen} onRequestClose={closeModal} contentLabel="Example Modal" overlayClassName="modal-overlay" className="modal-content">
        <h2>Square Info</h2>
        <button onClick={closeModal}>Close</button>
      </Modal>
        
    </div>        
  ); 

}

export default Home

getInfo.map returns a board of squares, I'd like to open a modal once users click each of the squares fetching information read from database.

CodePudding user response:

The solution I found:

 const [modalData, setModalData] = useState('');  
 const [readInfo, setReadInfo] = useState([]);  
 const findModalId = async () => {
  const dbRef = ref(database, 'id/'   '' modalData '');
  onValue(dbRef, (snapshot) => {
   const data = snapshot.val();           
   setReadInfo(data);       
  });
 };      
 useEffect(() => {findModalId();}, [modalData]);

  return (       
    <div className="grid-container">
      
      {getInfo.map((id, value) => <div className='grid-item' key={value.toString()} title={id.title} onClick={()=> {setModalData(value); findModalId(); openModal();}} style={{ backgroundImage: 'url('   id.imgURL   ')', backgroundSize: "cover", backgroundRepeat: "no-repeat", backgroundPosition: "center", }}></div>)}
        
      <Modal closeTimeoutMS={500} isOpen={modalIsOpen} onRequestClose={closeModal} contentLabel="Example Modal" overlayClassName="modal-overlay" className="modal-content">
        <h2>Member Info</h2>       
        {readInfo.title} 
        <button onClick={closeModal}>Close</button>
      </Modal>  
  • Related