0

I have a component 'ForumComponent.js' that displays forums that are received using a url from spring boot to make a get api call to the database. The api call returns the following:

[
    {
        "id": 1,
        "bookName": "Lord of the Flies",
        "bookImage": "../images/forum/lordoftheflies.jpg",
        "description": "The plot concerns a group of British boys who are stranded on an uninhabited island and their disastrous attempts to govern themselves"
    },
    {
        "id": 2,
        "bookName": "It",
        "bookImage": "../images/forum/it.jpg",
        "description": "It is a 1986 horror novel by American author Stephen King"
    },
    {
        "id": 3,
        "bookName": "Alice In Wonderland",
        "bookImage": "../images/forum/aliceinwonderland.jpg",
        "description": "Girl falls into another world."
    }
]

The 'bookImage' property contains a string with the location of the image saved locally inside a folder 'forum' inside another folder 'images'.

My problem is that the image box doesn't display the 'bookImage' and I haven't been able to figure out how to do so. The 'bookName' and 'description' are displayed.

Here is the component that displays the forums.

ForumComponent.js:

const [forums, setForums] = useState([]);
const REST_API_URL = "get url here";

useEffect(() => {
        axios.get(REST_API_URL).then((response) => {
          setForums(response.data);
        });
}, []);

function ForumComponent() {

   return (
        <div>
            <h2>Forum</h2>
            <table>
                <thead>
                    <tr>
                        <th>Book Name</th>
                        <th>Book Image</th>
                        <th>Description</th>
                    </tr>
                </thead>

                <tbody>
                {
                    forums.map((forum, index) => (
                      <tr key = {index}>
                         <td>{forum.bookName}</td>
                         <td><img src={forum.bookImage} height={100} width={100} alt=""/></td>
                         <td>{forum.description}</td>        
                      </tr>
                    ))
                }
                </tbody>
            </table>
            <IfCanPost/>   
        </div>   
    ) 

}

export default ForumComponent;

I know you can import the images but I want to be able to display images dynamically but I'm not sure how to go about doing that. Any help or links to information that can help is appreciated.

Here is how the React directory structure looks:

src
  |_components
             |_ForumComponent.js
  |_images
         |_forum
               |_aliceinwonderland.jpg
               |_it.jpg
               |_lordofflies.jpg

  |_App.css
  |_App.js
  |_App.test.js
  |_index.css
  |_index.js
  etc....

0 Answers0