Guide on dynamically adding images in React.js based on their filenames

Currently, I am in the process of implementing a language selection feature and I need to incorporate flags. Initially, I attempted to use Unicode emojis for flags, but unfortunately, they did not display properly when retrieved from React variables. As a workaround, I have now obtained PNG images of all the required flags.

My setup includes an array of languages with 'name' and 'value' properties. The 'value' property denotes the locale code, as well as the name of the corresponding image file:

languages: [
  {
    name: 'Swedish',
    value: 'sv_SE'
  },
  {
    name: 'English',
    value: 'en_US'
  },
  ...
]

In addition, I have imported the necessary files using these statements:

import sv_SE from './flags/sv_SE.png'
import en_US from './flags/en_US.png'

Within my code, the img tag is structured as follows:


languages.map((lang) => (
   <img src={ sv_SE } alt={ lang.value }/>
)

At the moment, only the Swedish flag is displaying. However, I would like the flag image to correspond to each respective element in the array. Do you have any suggestions or alternative solutions that could be beneficial in this scenario? Thank you for your time and assistance!

Answer №1

To simplify your code, consider using a single object where each imageSource is referenced by a specific key.

import frenchFlag from './flags/france.png'
import germanFlag from './flags/germany.png'

const flags = {
  france: frenchFlag,
  germany: germanFlag
}

...
languages.map((lang) => (
   <img src={ flags[lang.value] } alt={ lang.value }/>
)
...

Answer №2

Give this a shot:

languages.map((l) => (
   <img src={ `./icons/${l.value}.png` } alt={ l.value }/>
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Material-UI now offers extensive support for babel-plugin-react-css-modules, allowing for easier styling in React

material-ui: v4.8.2 react: v16.12.0 When using babel-plugin-react-css-modules with an rtl app, I initially tried to utilize the injectFirst option but encountered a warning message stating: Material-UI: you cannot use the jss and injectFirst props at th ...

Which styles are necessary to create a unique Material UI palette?

In my components, I utilize the MuiThemeProvider to customize a button. This is necessary because only "primary" or "secondary" can be used instead of a custom palette name. The code for this setup is as follows: import React from "react"; import { badThe ...

"Proceeding without waiting for resolution from a Promise's `.then`

I am currently integrating Google Identity Services for login on my website. I am facing an issue where the .then function is being executed before the Promise returned by the async function is resolved. I have temporarily used setTimeout to manage this, b ...

Having difficulty transferring navigation props between screens using react-navigation

Within my ContactList component, I have utilized a map to render various items. Each item includes a thumbnail and the desired functionality is that upon clicking on the thumbnail, the user should be directed to a new screen referred to as UserDetailsScree ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

Determining the installation duration of the React Native screen

Several questions have been asked about this topic, but none of them seem to have a definitive answer. What I am looking to do is calculate the time it takes to navigate to a screen. The timer will start here: navigation.navigate("SomePage") Essentially, ...

Searching using ReactJS when the user changes the input

I'm facing an issue with the search functionality in my ReactJS application. Every time a user types a letter in the textfield, the "searchHandler" function is triggered, making multiple calls to the API for a single term like "Lorem". This results in ...

Is it possible to use async in the onChange handler of a React event?

Can async be used to pause execution until a function completes within an onChange event? Here is an example: const onChange = async (e) => { console.log(current[e.target.name]); await setCurrent({ ...current, [e.target.name]: e.targe ...

Develop a customized interface for exporting styled components

I am struggling to figure out how to export an interface that includes both the built-in Styled Components props (such as as) and my custom properties. Scenario I have created a styled component named CustomTypography which allows for adding typographic s ...

Having trouble incorporating a title in the header section

I encountered an issue while attempting to include the Fragment, title, and Head. When these are added, an error occurs but when removed, the page displays correctly. I have searched for a solution to this problem but couldn't find anything. import ...

Steps to resolve the issue of being unable to destructure property temperatureData from 'undefined' or 'null' in a React application without using a class component

CODE: const { temperatureData } = state; return ( <> <div className="flex flex-row"> {temperatureData.map((item, i) => ( <div className="flex flex-auto rounded justify-center items-center te ...

Transitioning from CRA to Gatsby caused issues with JSS plugins

When working with `create-react-app`, I utilized `react-jss` because the `jss-plugin-expand` plugin was not included by default. I had `` set up and everything was functioning properly. However, upon switching to Gatsby, the exact same configuration stoppe ...

Leaflet GeoJSON Turf library encountered an error: Invalid coordinates for LatLng object: (undefined, undefined)

After setting the return to null for the component and condition in question to check the data being returned, I thoroughly examined the coordinates arrays without finding any issues. The data comes in as an array of geometry collections containing linest ...

How can the Domain attribute of the Express.js cookie setter be utilized to share a cookie across multiple domains effectively?

Consider a scenario where you have the cookie setter code as follows: res.cookie('name', 'tobi', { secure: true, httpOnly: false, sameSite: 'None', domain: '.example1.com' }); To make the cookie ac ...

Trouble with Next Js Image 'fill' property causing images to not show up on the page

Currently tackling a project involving a simple grid layout with images and text. I'm using Next 13.4.7 along with Tailwind CSS. However, I've encountered an issue when trying to import an image using the Next Image component with the fill prop - ...

What are the differences between using the open prop and conditionally rendering a Material-UI Modal component?

Is there a difference in using the open prop or conditionally rendering Material-UI's Modal component and its built components? The closing transition may be lost, but are there any performance advantages when dealing with multiple Modals? Example wi ...

Exploring the Transition from React.js with Material UI to Next.js for Server-Side Rendering: A Comparison of Tailwind CSS, Material UI, and Chakra UI

Currently, I am in the process of moving my React.js application with Material UI components to Next.js for server-side rendering (SSR) while considering some UI changes. In my research, I have come across three UI frameworks: Material UI, Chakra UI, and T ...

Accessing loop variables in Render and passing them into componentDidMount() in ReactJS to include as a query parameter in an API call

Within the render function, I am using a loop to rotate an array of coordinates in order to position markers on a map. {coords.map(({ lat, lng }, index) => (code goes here and so on))} I intend to replace query parameters with the variable generated f ...

Error: The integer provided in the Stripe payment form is invalid in the

I'm encountering an error that I can't seem to figure out. I believe I'm following the documentation correctly, but Stripe is not able to recognize the value. Have I overlooked something important here? https://stripe.com/docs/api/payment_i ...

Unleashing the power of async/await in React: A comprehensive guide

Looking to simplify my code, I am interested in implementing async and await for the following code snippet. However, I am unsure of how to proceed. Any examples would be greatly appreciated. deletePost = (post) => { var post_id = post; try { ...