so i have store my image urls in my mySql database and want to show him in my website
i want to separate these 2 datas there is comma between them.
17-12-2022-144-download (2).jpg,17-12-2022-43-download.jpg
and store them in a useState or a variable so i can assign them to the <img tag.
>Solution :
To separate the image URLs by using React JS, you can use the String.prototype.split() method to split the string of image URLs at the comma character.
Here is an example of how you can do this:
import React, { useState } from 'react';
function MyComponent() {
const [imageUrls, setImageUrls] = useState([]);
// Fetch the image URLs from your database
const imageUrlString = "17-12-2022-144-download (2).jpg,17-12-2022-43-download.jpg";
// Split the string at the comma character
const urlArray = imageUrlString.split(',');
// Set the imageUrls state variable to the array of image URLs
setImageUrls(urlArray);
return (
<div>
{imageUrls.map((url, index) => (
<img key={index} src={url} alt="My image" />
))}
</div>
);
}
In this example, we first import the useState hook from the react library. We then define a state variable called imageUrls using the useState hook.
Next, we fetch the image URLs from the database and store them in a variable called imageUrlString. We then use the split() method to split the string at the comma character, and store the resulting array in a variable called urlArray.
Finally, we use the setImageUrls function to set the imageUrls state variable to the array of image URLs.
We can then use the imageUrls state variable in the JSX of our component to render the images. In the example above, we use the map() function to iterate over the array of image URLs and render an img element for each URL.
