Navigating the world of interpolation in React

Within the img tag, there is an attribute called src, with a value of "images/education.jpg". The image details are stored in an array as shown below:

const itemData = [
  {
    img: "image",
    title: "Education",
    src: "education.jpg",
  },
  {
    img: "image2",
    title: "Cooking",
    src: "cooking.jpg",
},
];

I am trying to figure out how to dynamically set the src attribute using string interpolation like

src="images/{item.src}"
. However, I understand that this syntax is incorrect.

 {itemData.map((item) => (
      <ImageListItem key={item.img}>
        <img            
        src="images/education.jpg"
        />

Answer №1

Here are a couple of ways you can achieve this:

{itemData.map((item, i) => (
  <ImageListItem key={item.img}>
    <img src={"images/" + itemData[i].src} />
  </ImageListItem>
)}

Alternatively, you can also try:

{itemData.map((item, i) => (
  <ImageListItem key={item.img}>
    <img src={`images/${itemData[i].src}`} />
  </ImageListItem>
)}

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

Encountering CORS issue specifically on Safari, yet functioning without any trouble on other

While working on a simple project, I came across an issue specifically with Safari browser. The error message I received was: '[Error] Fetch API cannot load https://randomuser.me/api due to access control checks.' The project is built using Nex ...

ReactJS component disappearing behind the Navbar

When using my React app, I have a navigation bar at the top. The Navbar component is called in App.js, and the code snippet below shows how it is implemented. export default function App() { return ( <Router> <Fragment> ...

What is the proper way to integrate @googlemaps/js-api-loader into a React application?

I'm interested in using the Google Maps API with React. After reading an informative article, I discovered that there are recently released packages available for this purpose. However, even after reviewing examples, I'm still unsure about how ...

React conditional statement malfunctioning when conditions are greater than

Something seems off here, as a seemingly simple condition is not evaluating to true: const [mousePressing, setMousePressing] = useState(false) const [longPressSuccess, setLongPressSuccess] = useState(false) const delayTime = 1000; const [pres ...

What are the ideal scenarios for using a MobX observable over a React state variable?

I'm feeling a bit uncertain. My go-to is usually observables for tracking variables that impact rendering, but I'm questioning whether it's the best approach. How can I determine when it's more appropriate to use state over an observabl ...

Utilizing Material-UI ThemeProvider and createGenerateClassName for Preventing Class Name Overlap

Is there a way to prevent conflicts in a React application using material-ui classNames from makeStyles when including a package that also uses the same naming conventions, resulting in multiple conflicting .jss1, .jss2 styles on the rendered page? Both th ...

Having trouble with `Routes.push()` in NextJS?

When attempting to access the app dashboard without authentication, I wanted to redirect the user to the homepage. However, I encountered an issue with Route.push() not working as expected. To test this behavior further, I modified Router.push('/&apo ...

"Encountering an issue with Next.js due to npm dependencies importing CSS files

I am working on a next.js project and I am trying to incorporate a component from npm that internally imports typeface-montserrat. However, when trying to do so, Next.js is throwing an error: <path>/node_modules/typeface-montserrate/index.css:2 @fo ...

Connecting the material-ui dropdown to a table

Is there a way to connect a react material-ui dropdown to a table? I am working on a project where I have a drop-down list containing countries and a table displaying country names and their corresponding capital cities. The goal is to update the table b ...

The deployment of the React Single Page Application on Netlify encountered errors during the

Whenever I try to deploy the website after successfully running it locally, I encounter this error message in the log file: In between the errors Failed to compile. and npm ERR! code ELIFECYCLE, there are some warnings about using == instead of === and ha ...

Secured paths authenticate user API access

Currently, I am attempting to verify my protected router by making an API call to check the user. However, despite my efforts, it is not functioning as expected. Below is my code snippet. I am using React version 17, react-router-dom 6, and TypeScript. Th ...

The tool tip feature is not recognizing line breaks

I've encountered an issue with the tooltip in my project. Despite trying various solutions found on stackoverflow, I am still unable to resolve it. In my ReactJS application, I am dynamically creating elements using createElement and applying the too ...

React components can be used to dynamically render and display an array of objects through methods like reduce and

Here's the scenario at hand: (https://codesandbox.io/s/8p21n6p09l) I have an array of objects (referred to as modules) structured like this: const modules = [ { thematicArea: "Topic 1", id: 1, name: "Building assertive attitude", d ...

Ensuring Email Authenticity in React Native

I'm currently working on email validation and have a specific condition in mind. If the email textbox is empty, I want to return true When the email textbox is not empty, I need to check if the input is a valid email address If the email is n ...

Production facing issues with Clerk Middleware on Next 12.2.2 due to crashes

I've been struggling to understand the root cause of this issue, but I'm currently working on implementing Clerk Authentication using NextJS 12.2.2. Everything works fine in my development environment, but as soon as I move to production, my site ...

"error": "Connection Failure", "type": "AxiosError",

I recently worked on a project using Vue.js and making API requests with axios. Here is my code snippet: axios({ method: "POST", url: http://abcd.com:5000/start-recording?roomId=${this.roomId}, headers: { 'Access-Control-Allow-Origin': ...

What is the best way to implement custom pagination in Material UI?

<Pagination count={35} variant="outlined" shape="rounded" color="primary"/> Although the default background and text colors are set, I am unable to customize them. I have attempted to change the colors without success. ...

Check if the user is null using React's useEffect hook and then perform a

I am currently working on implementing a protected route in Next JS. I have included a useEffect to redirect to the sign-in page if there is no user detected. const analytics = () => { const { userLoaded, user, signOut, session, userDetails, subscri ...

Creating unique backgrounds for multiple webpages with React (Ensuring backgrounds stay consistent after refreshing)

Home.js file const Home = () => { var navigate = useNavigate(); const changeBackground = () => { navigate("/builder"); var htmlElement = document.getElementsByTagName('html'); htmlElement[0].style.backgr ...

Discover the steps to execute an asynchronous function from a separate file

With the help of Next.JS, I am developing an admin panel dashboard for my web application. To access the database, I am using Prisma client along with MongoDB. I am facing an issue where I cannot display the total number of users currently in the database ...