Take Image from API and store it in a object

439 Views Asked by At

I am trying to use react image gallery which is pretty good for me. Here I am kinda stuck on something as I am not good with react so any help would be appreciated. Here I am taking images from api and I get the image in my frontend.

{restaurant.menu?.map((men) => (
         <ListGroup.Item key={men.id}>
     <Image src={men.image} alt={men.name} style={{height:'250px', width:'1800px'}} fluid />
                                                
          </ListGroup.Item>
 ))}

I want to pass images like this items, How can I do this? I have menu object in restaurant.menu and if I map through this then I get the image and I want to pass those image here

import ImageGallery from "react-image-gallery";
import "react-image-gallery/styles/css/image-gallery.css";

const images = [
        {
          original: 'https://picsum.photos/id/1018/1000/600/',
        },
        {
          original: 'https://picsum.photos/id/1015/1000/600/',
        },
        {
          original: 'https://picsum.photos/id/1019/1000/600/',
         
        },
      ];

<ImageGallery items={images} />

this is my fullcode

import React, {useEffect, useState} from 'react'
import { Link } from 'react-router-dom'
import { Row, Col, Image, ListGroup, Button, Card, Form } from 'react-bootstrap'
import Rating from '../components/Rating'
import products from '../products'
import { useDispatch, useSelector } from 'react-redux'
import { listRestaurantDetails } from '../actions/restaurantActions'
import ImageGallery from "react-image-gallery";
import "react-image-gallery/styles/css/image-gallery.css";
import Loader from '../components/Loader'
import Message from '../components/Message'
import Faq from "react-faq-component";



function ProductScreen({ match }) {

    

    

    const data = {
        title: "FAQ",
        rows: [
            {
                title: "Lorem ipsum dolor sit amet,",
                content: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed tempor sem. Aenean vel turpis feugiat,
                  ultricies metus at, consequat velit. Curabitur est nibh, varius in tellus nec, mattis pulvinar metus.
                  In maximus cursus lorem, nec laoreet velit eleifend vel. Ut aliquet mauris tortor, sed egestas libero interdum vitae.
                  Fusce sed commodo purus, at tempus turpis.`,
            },
            {
                title: "Nunc maximus, magna at ultricies elementum",
                content:
                    "Nunc maximus, magna at ultricies elementum, risus turpis vulputate quam, vitae convallis ex tortor sed dolor.",
            },
            {
                title: "Curabitur laoreet, mauris vel blandit fringilla",
                content: `Curabitur laoreet, mauris vel blandit fringilla, leo elit rhoncus nunc, ac sagittis leo elit vel lorem.
                Fusce tempor lacus ut libero posuere viverra. Nunc velit dolor, tincidunt at varius vel, laoreet vel quam.
                Sed dolor urna, lobortis in arcu auctor, tincidunt mattis ante. Vivamus venenatis ultricies nibh in volutpat.
                Cras eu metus quis leo vestibulum feugiat nec sagittis lacus.Mauris vulputate arcu sed massa euismod dignissim. `,
            },
            {
                title: "What is the package version",
                content: 'ok',
            },
        ],
    };
    
    const styles = {
        // bgColor: 'white',
        titleTextColor: "black",
        rowTitleColor: "blue",
        // rowContentColor: 'grey',
        arrowColor: "red",
    };
    
    const config = {
        // animate: true,
        // arrowIcon: "V",
        // tabFocus: true
    };

    // const images = [
    //     {
    //       original: 'https://picsum.photos/id/1018/1000/600/',
    //     },
    //     {
    //       original: 'https://picsum.photos/id/1015/1000/600/',
    //     },
    //     {
    //       original: 'https://picsum.photos/id/1019/1000/600/',
         
    //     },
    //   ];

    // const images = restaurant.menu.map((men.image) => ({ original: men.image }))
    const dispatch = useDispatch()

    const restaurantDetails = useSelector(state => state.restaurantDetails)

    const { loading, error, restaurant } = restaurantDetails
    
    useEffect(() => {
        dispatch(listRestaurantDetails(match.params.id))
    }, [dispatch, match])

    
    return (
        <div>
            <div>
                 <div>
                     <br />
                     {loading ?
                        <Loader />
                        : error 
                            ? <Message severity='error'>{error}</Message>
                            :
                            <Row>
                                <Col md={12}>
                                    <Image src={restaurant.banner_image} alt={restaurant.name} style={{height:'250px', width:'1800px'}} fluid />
                                </Col>


                                
                                <Col md={6}>
                                
                                <Link to='/' className='btn btn-outline-dark my-3'>Go Back</Link>
                                <br />
                                    <ListGroup variant="flush">
                                        <ListGroup.Item>
                                            <h3>{restaurant.name}</h3>
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            <Button variant='outline-dark' href={`https://maps.google.com/?q=${restaurant.name}`}>Get Directions </Button>
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            <Rating value={restaurant.rating} text={`${restaurant.numReviews} reviews`} color={'#f8e825'} />
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            {restaurant.restaurant_type} Restaurant
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                           Minimum {restaurant.approx_two_people} BDT for two people 
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Total Available {restaurant.available_capacity} 
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Live {restaurant.live_capacity} People
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Notice {restaurant.notice} 
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Emergency Notice {restaurant.emergency_notice} 
                                        </ListGroup.Item>


                                        <ListGroup.Item>
                                         Offer Available {restaurant.isOffer} 
                                        </ListGroup.Item>


                                        <ListGroup.Item>
                                            Offer Title {restaurant.offer_title} 
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Number {restaurant.number} 
                                        </ListGroup.Item>

                                      

                                        <ListGroup.Item>
                                        <Image src={restaurant.qr_code} alt={restaurant.name} style={{height:'100px', width:'100px'}} fluid />
                                        </ListGroup.Item>
                                     
                                        <ListGroup.Item>
                                        {restaurant.hygiene_option?.map((hygiene) => (  
                                           <strong>{hygiene.name}<br /></strong>))}
                                        </ListGroup.Item>


                                        <ListGroup.Item>
                                        {restaurant.schedule?.map((schedul) => (  
                                            
                                           <strong>{schedul.from_hour}<br /></strong>
                                           
                                           ))}
                                        </ListGroup.Item>


                                        <ListGroup.Item>
                                        {restaurant.available_payment_option?.map((payment) => (  
                                           <strong>{payment.name}<br /></strong>))}
                                        </ListGroup.Item>


                                        <ListGroup.Item>
                                        {restaurant.feature_option?.map((feature) => (  
                                           <strong>{feature.name}<br /></strong>))}
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Description: {restaurant.description}
                                        </ListGroup.Item>


                                        {restaurant.menu?.map((men) => (
                                            <ListGroup.Item key={men.id}>
                                                
                                                <Image src={men.image} alt={men.name} style={{height:'250px', width:'1800px'}} fluid />
                                                
                                            </ListGroup.Item>
                                            
                                        ))}



                                        {restaurant.faq?.map((f) => (
                                            <ListGroup.Item key={f.id}>
                                                Question - <strong>{f.question}</strong>
                                                <br />
                                                Answer - <strong>{f.answer}</strong>                    
                                            </ListGroup.Item>
                                            
                                        ))}


                                        {restaurant.reviews?.map((review) => (
                                            <ListGroup.Item key={review._id}>
                                                <strong>{review.name}</strong>
                                                <Rating value={review.rating} color='#f8e825' />
                                                <strong>{review.createdAt.substring(0, 10)}</strong>
                                                <br />
                                                <strong>{review.comment}</strong>
                                            </ListGroup.Item>
                                            
                                        ))}
                                    </ListGroup>
                                </Col>

                                <Row style={{marginTop: 50, marginBottom:50}}>
                                <iframe src={restaurant.embedded_map_link}
                                style={{ height:400, width:600}}></iframe>
                                </Row>

                                <Col md={3}>
                                <br />
                                <br />                            
                                    {/* <Card>  
                                        <ListGroup variant='flush'>
                                            <ListGroup.Item>
                                                <Button
                                                variant='outline-dark'
                                                    // onClick={addToCartHandler}
                                                    className='btn-block'
                                                    disabled={restaurant.countInStock == 0}
                                                    type='button'>
                                                    Add to Cart
                                                </Button>
                                            </ListGroup.Item>
                                        </ListGroup>
                                    </Card> */}
                                    <br />
                                </Col>
                                <br />
                                <br />

                                 
                                     <Faq
                                     data={data}
                                     styles={styles}
                                     config={config}
                                     />
                                         
                                            
                                      
                               
                            </Row>



                    }
                     
                            

                           
                                    
                        </div>
              


        </div >
            
        </div>
    )
}

export default ProductScreen
1

There are 1 best solutions below

4
On

Firstly, you need to extract all your image sources from restaurant.menu and format them with a new list that is aligned with react-image-gallery data

const images = restaurant.menu.map((men.image) => ({ original: men.image }))

and then you can pass it to where you call ImageGallery

<ImageGallery items={images} />

Integrated with your code

const RestaurantImages = ({ restaurantMenu }) => {
   if(!restaurant.menu) {
      return null;
   }
   
   const images = restaurant.menu.map((men.image) => ({ original: men.image }))
   return <ImageGallery items={images} />
}  

Replace this

{restaurant.menu?.map((men) => (
         <ListGroup.Item key={men.id}>
     <Image src={men.image} alt={men.name} style={{height:'250px', width:'1800px'}} fluid />                                 
          </ListGroup.Item>
 ))}

with this

<RestaurantImages restaurantMenu={restaurant.menu}>

Your edited full code

import React, {useEffect, useState} from 'react'
import { Link } from 'react-router-dom'
import { Row, Col, Image, ListGroup, Button, Card, Form } from 'react-bootstrap'
import Rating from '../components/Rating'
import products from '../products'
import { useDispatch, useSelector } from 'react-redux'
import { listRestaurantDetails } from '../actions/restaurantActions'
import ImageGallery from "react-image-gallery";
import "react-image-gallery/styles/css/image-gallery.css";
import Loader from '../components/Loader'
import Message from '../components/Message'
import Faq from "react-faq-component";

const RestaurantImages = ({ restaurantMenu }) => {
   if(!restaurant.menu) {
      return null;
   }
   
   const images = restaurant.menu.map((men.image) => ({ original: men.image }))
   return <ImageGallery items={images} />
}


function ProductScreen({ match }) {

    

    

    const data = {
        title: "FAQ",
        rows: [
            {
                title: "Lorem ipsum dolor sit amet,",
                content: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed tempor sem. Aenean vel turpis feugiat,
                  ultricies metus at, consequat velit. Curabitur est nibh, varius in tellus nec, mattis pulvinar metus.
                  In maximus cursus lorem, nec laoreet velit eleifend vel. Ut aliquet mauris tortor, sed egestas libero interdum vitae.
                  Fusce sed commodo purus, at tempus turpis.`,
            },
            {
                title: "Nunc maximus, magna at ultricies elementum",
                content:
                    "Nunc maximus, magna at ultricies elementum, risus turpis vulputate quam, vitae convallis ex tortor sed dolor.",
            },
            {
                title: "Curabitur laoreet, mauris vel blandit fringilla",
                content: `Curabitur laoreet, mauris vel blandit fringilla, leo elit rhoncus nunc, ac sagittis leo elit vel lorem.
                Fusce tempor lacus ut libero posuere viverra. Nunc velit dolor, tincidunt at varius vel, laoreet vel quam.
                Sed dolor urna, lobortis in arcu auctor, tincidunt mattis ante. Vivamus venenatis ultricies nibh in volutpat.
                Cras eu metus quis leo vestibulum feugiat nec sagittis lacus.Mauris vulputate arcu sed massa euismod dignissim. `,
            },
            {
                title: "What is the package version",
                content: 'ok',
            },
        ],
    };
    
    const styles = {
        // bgColor: 'white',
        titleTextColor: "black",
        rowTitleColor: "blue",
        // rowContentColor: 'grey',
        arrowColor: "red",
    };
    
    const config = {
        // animate: true,
        // arrowIcon: "V",
        // tabFocus: true
    };

    // const images = [
    //     {
    //       original: 'https://picsum.photos/id/1018/1000/600/',
    //     },
    //     {
    //       original: 'https://picsum.photos/id/1015/1000/600/',
    //     },
    //     {
    //       original: 'https://picsum.photos/id/1019/1000/600/',
         
    //     },
    //   ];

    // const images = restaurant.menu.map((men.image) => ({ original: men.image }))
    const dispatch = useDispatch()

    const restaurantDetails = useSelector(state => state.restaurantDetails)

    const { loading, error, restaurant } = restaurantDetails
    
    useEffect(() => {
        dispatch(listRestaurantDetails(match.params.id))
    }, [dispatch, match])

    
    return (
        <div>
            <div>
                 <div>
                     <br />
                     {loading ?
                        <Loader />
                        : error 
                            ? <Message severity='error'>{error}</Message>
                            :
                            <Row>
                                <Col md={12}>
                                    <Image src={restaurant.banner_image} alt={restaurant.name} style={{height:'250px', width:'1800px'}} fluid />
                                </Col>


                                
                                <Col md={6}>
                                
                                <Link to='/' className='btn btn-outline-dark my-3'>Go Back</Link>
                                <br />
                                    <ListGroup variant="flush">
                                        <ListGroup.Item>
                                            <h3>{restaurant.name}</h3>
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            <Button variant='outline-dark' href={`https://maps.google.com/?q=${restaurant.name}`}>Get Directions </Button>
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            <Rating value={restaurant.rating} text={`${restaurant.numReviews} reviews`} color={'#f8e825'} />
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            {restaurant.restaurant_type} Restaurant
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                           Minimum {restaurant.approx_two_people} BDT for two people 
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Total Available {restaurant.available_capacity} 
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Live {restaurant.live_capacity} People
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Notice {restaurant.notice} 
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Emergency Notice {restaurant.emergency_notice} 
                                        </ListGroup.Item>


                                        <ListGroup.Item>
                                         Offer Available {restaurant.isOffer} 
                                        </ListGroup.Item>


                                        <ListGroup.Item>
                                            Offer Title {restaurant.offer_title} 
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Number {restaurant.number} 
                                        </ListGroup.Item>

                                      

                                        <ListGroup.Item>
                                        <Image src={restaurant.qr_code} alt={restaurant.name} style={{height:'100px', width:'100px'}} fluid />
                                        </ListGroup.Item>
                                     
                                        <ListGroup.Item>
                                        {restaurant.hygiene_option?.map((hygiene) => (  
                                           <strong>{hygiene.name}<br /></strong>))}
                                        </ListGroup.Item>


                                        <ListGroup.Item>
                                        {restaurant.schedule?.map((schedul) => (  
                                            
                                           <strong>{schedul.from_hour}<br /></strong>
                                           
                                           ))}
                                        </ListGroup.Item>


                                        <ListGroup.Item>
                                        {restaurant.available_payment_option?.map((payment) => (  
                                           <strong>{payment.name}<br /></strong>))}
                                        </ListGroup.Item>


                                        <ListGroup.Item>
                                        {restaurant.feature_option?.map((feature) => (  
                                           <strong>{feature.name}<br /></strong>))}
                                        </ListGroup.Item>

                                        <ListGroup.Item>
                                            Description: {restaurant.description}
                                        </ListGroup.Item>


                                        <RestaurantImages restaurantMenu={restaurant.menu}/>



                                        {restaurant.faq?.map((f) => (
                                            <ListGroup.Item key={f.id}>
                                                Question - <strong>{f.question}</strong>
                                                <br />
                                                Answer - <strong>{f.answer}</strong>                    
                                            </ListGroup.Item>
                                            
                                        ))}


                                        {restaurant.reviews?.map((review) => (
                                            <ListGroup.Item key={review._id}>
                                                <strong>{review.name}</strong>
                                                <Rating value={review.rating} color='#f8e825' />
                                                <strong>{review.createdAt.substring(0, 10)}</strong>
                                                <br />
                                                <strong>{review.comment}</strong>
                                            </ListGroup.Item>
                                            
                                        ))}
                                    </ListGroup>
                                </Col>

                                <Row style={{marginTop: 50, marginBottom:50}}>
                                <iframe src={restaurant.embedded_map_link}
                                style={{ height:400, width:600}}></iframe>
                                </Row>

                                <Col md={3}>
                                <br />
                                <br />                            
                                    {/* <Card>  
                                        <ListGroup variant='flush'>
                                            <ListGroup.Item>
                                                <Button
                                                variant='outline-dark'
                                                    // onClick={addToCartHandler}
                                                    className='btn-block'
                                                    disabled={restaurant.countInStock == 0}
                                                    type='button'>
                                                    Add to Cart
                                                </Button>
                                            </ListGroup.Item>
                                        </ListGroup>
                                    </Card> */}
                                    <br />
                                </Col>
                                <br />
                                <br />

                                 
                                     <Faq
                                     data={data}
                                     styles={styles}
                                     config={config}
                                     />
                                         
                                            
                                      
                               
                            </Row>



                    }
                     
                            

                           
                                    
                        </div>
              


        </div >
            
        </div>
    )
}

export default ProductScreen