Image from json file is not displayed on the website

Viewed 650

I want to fetch images from json to javascript function but instead of displaying the image it instead just displays the name of image file. Below is the javascript function

            import React from "react";
        import IosAppName from './appStoreData.json';
        import './Ios_search.css';
        import {useState} from 'react';

        function Ios_search(){
            const[searchTerm, setSearchTerm] = useState('')
            return(
                <div className='ios'>
                    <input type='text' placeholder='Search' onChange={event => {setSearchTerm(event.target.value)}}></input>
                    {IosAppName.filter(
                        app_name =>{
                            if(searchTerm == '') return ''
                            else if(app_name.appStore.toLowerCase().includes(searchTerm.toLowerCase())) return  app_name
                        }
                        
                    )

                    .map((all_app_names) => {return <p>{all_app_names.appStore} {all_app_names.image}</p>})}
                </div>
            );
        }

        export default Ios_search;

And this is the dummy data

[
    
    {"appStore":"Cardguard",
    "image": "AS.jpg"},
    {"appStore":"Temp"},
    {"appStore":"Tempsoft"},
    {"appStore":"Stim"},
    {"appStore":"Tin"},
    {"appStore":"Aerified"},
    {"appStore":"Ventosanzap"},
    ]

this is what it looks like when searched- Searchbar

2 Answers

To display an image in a website you should use the <img> tag. Right now {all_app_names.image} lives inside a <p> tag. That's why it simply shows the files name. You can re-write this to be

 .map((all_app_names) => {return <p>{all_app_names.appStore} <img src={all_app_names.image}/> </p>})}

However, something to note, the src attribute in the image tag, requires the proper direct path value or direct link.

If the direct path value is incorrect, it will display an empty image placeholder.

Depending where the image you are fetching is stored, you may have to tweak your database attained value, a little bit. You can read more about img tags here: https://www.w3schools.com/tags/tag_img.asp

I had this problem too but was able to solve it by just moving my images to the public folder and fetching them from there. This is not only easier, it also eliminates complex file path hierarchy.

Related