Background image in tailwindcss using dynamic url (React.js) - javascript

I have an image url fetched from an API and I want to display it as a background image. Is there any way I can implement this with tailwindcss or should I use styles attribute?

I think the best solution is to do what you suggested and use a style attribute. Tailwind CSS doesn't really deal with dynamic data, but rather with class names to add predefined styles to your element. The best you could without using the style attribute is to conditionally add/remove classNames from an element, but that would require you to know the image URL ahead of time, which defeats the purpose of getting it from an API.
I would do:
style={{backgroundImage: `url(${fetchedImgSrc})`}}
Edit:
It looks like you can actually use Tailwind to do something similar to the code above as per https://tailwindcss.com/docs/background-image.
The code looks like:
<div class="bg-[url('/img/hero-pattern.svg')]">
<!-- ... -->
</div>

I think I have found a solution other than simply using a style attribute.
<div
style={{'var(--image-url)': fetchedUrl}}
className='bg-[image:var(--image-url)]'>
<!-- ... -->
</div>
This works perfectly fine.
Although it looks a bit tedious, it can be used to enable the background image on hover, focus, etc. In which the style attribute is incapable of.
className='hover:bg-[image:var(--image-url)] focus:bg-[image:var(--image-url)] ...'
This application of custom properties can be used for implementing dynamic values with tailwind like colors fetched from an API.
<div
style={{'var(--color)': fetchedColor}}
className='text-[color:var(--color)]'>
<!-- ... -->
</div>

you can just use backgroundImage in Style
const bag2 = "https://via.placeholder.com/500"
<div
className = "someting"
style={{backgroundImage: `url(${bag2})`}}
</div>

Even with the latest implementation of the arbitrary-values - it seems like it's not working for Dynamic URLs.
In my case image was coming from an API. If it is the case, stick to style attribute.
In the solution below - bgImage is a prop.
<div className={`justify-center bg-no-repeat bg-cover bg-center rounded-lg`}
style={{ backgroundImage: `url(${bgImage})`}} >
<!-- Children here-->
</div>

If you are having this same issue in 2022, then this is what helped me with tailwind version ^3.0.23. I just moved the image to the public folder and used the link in my tailwind.config.js like so backgroundImage: { 'cover-pic': "url('/public/img/cover_pic.jpg')" } where /public/img is the directory where I placed the image within the public folder, yours might different. and then called the css like so bg-cover-pic within my project, and that was all it took.

I just went to html to jsx online converter https://magic.reactjs.net/htmltojsx.htm the pasted what I copied from tailwind website -
<div class="bg-cover bg-center ..." style="background-image: url(...)"></div>
then I just copied my new generated jsx code-
style={{ backgroundImage: 'url(/about.jpg.webp)' }}

Related

How to call Dynamic Image in Background from API?

I am trying to call an Image dynamically from thesportsdb API.
After destructuring, I am trying to set the image in the background of this div. But It doesn't show the image. It only works when I add a static image in CSS. It's a react practice project and everything else is working fine.
How may I solve this?
<div style={{background: strStadiumThumb}} className="banner-img">
<img className='img-fluid' src={strTeamBadge} alt="" />
</div>
Firstly, please add the relevant code directly into the question, not pictures of code. Secondly, background isn't a valid div tag attribute. If you want to inline the background style, you can use the style attribute, which is an object property that lets you inline CSS styles into your element:
<div style={{ backgroundImage: `url(${strStadiumThumb})` }} className="banner-img>
...

VueJS: Do not show div if image doesn't exist

I am rendering some div and I have like to not show a div when an image is not there.
An example image is here: https://clips-media-assets2.twitch.tv/AT-cm%7C891283246-preview-480x272.jpg
I am thinking of something like this:
<div v-show="twItem.imageurl">{{twItem.title}}</div>
But it doesn't work. Any help would be appreciated.
This task is not primitive.
No matter if you use v-if or v-show, both compare the same thing, but the result is different. v-if="false" will not render the element at all, whilst v-show="false" will render it, but hidden. (display: none;)
The problem here is, that you simply check if the twItem.imageurl is set and NOT if the image was loaded.
What you might be able to do is using #load:
<template>
<div v-if="twItem.loaded">{{ twItem.title }}</div>
<image :src="twItem.imageurl" #load="twItem.loaded = true">
</template>
See here for a more detailed explanation: https://renatello.com/vue-js-image-loaded/
Use v-if instead of v-show.
<div v-if="twItem.imageurl">{{ twItem.title }}</div>

TailwindCSS + Nuxt background image

I am using TailwindCSS in a Nuxt project and I am trying to add a background image to a header element. The tailwindCSS official docs solution for this is the following : <div class="bg-fixed ..." style="background-image: url(...)"></div>
I have an images folder in the webpack assets folder where my bitcoin.jpg image lives.
I have tried using <header class="bg-fixed" style="background-image: url(~assets/images/bitcoin.jpg)"
This is not working, I have also tried classbinding, that doesn't work either. Anyone got an idea about a fix?
Thanks in advance!
Try this (EDIT: This doesn't work, scroll down):
<header class="bg-fixed" style="background-image: url(~#/assets/images/bitcoin.jpg)"
The ~ tells webpack to treat the url as a module request, then you need to use a correct alias. In nuxt, these are usually prefixed with #.
EDIT
I didn't realize that there's something strange going on under the hood with Webpack. That syntax works with src attributes, but Webpack won't do the path resolution for background-image.
Here's the real fix:
<header class="bg-fixed" :style="{'background-image': `url(${require('#/assets/images/bitcoin.jpg')})`}"
By using require, you signal to Webpack to use the file-loader to create the proper module path, and replace that in the url function.
Working example: https://codesandbox.io/s/late-mountain-zdw09?file=/pages/index.vue
Quote for reference:
In order for Webpack to return the correct asset paths, you need to use require('./relative/path/to/file.jpg'), which will get processed by file-loader and returns the resolved URL
Page where the quote is from: https://vuejs-templates.github.io/webpack/static.html
Ref: https://github.com/vuejs/vue-loader/issues/646
The header hasn't got any content, nor height or width so it is not displayed. And you can't see the background.
A working solution would be :
<div class="bg-fixed w-full" style="background-image: url('/images/bitcoin.jpg'); min-height: 200px;" />
I added 100% width and 200px min-height.
And also, you seemed to miss the single quotes around the image path.
bg-fixed isn't quite the best solution, you should try bg-cover or bg-contain with
bg-no-repeat
https://tailwindcss.com/docs/background-size#class-reference
package.json
"nuxt": "^3.0.0"
"#nuxtjs/tailwindcss": "^6.1.3"
1
<header class="bg-fixed bg-[url('assets/images/bitcoin.jpg')]"/>
2
<header class="bg-fixed" :style="{ backgroundImage: `url('assets/images/bitcoin.jpg')` }"/>
3
<header class="bg-fixed" :style="`background-image: url('assets/images/bitcoin.jpg')`"/>

Automatic margins when using css

If i used CSS my div automatically margins left and right if i use inline style its works perfect,i don't understand whats going when i use CSS
i'm using React.js
I'm trying to style with CSS,its gives auto margin to left and right
<div className="container">
<h1>hello</h1>
</div>
//CSS code
.container
background-color: lightblue;
}
//i'm using inline style its works perfect
``
<div style={{backgroundColor: 'blue'}}>
<h1>hello</h1>
</div>
``
I guess you have included bootstrap in your project and container is a bootstrap class, so it adds style from bootstrap library as well
Try using any other class name it will just work fine.
Please note, container is a bootstrap class, so it adds style from bootstrap library as and try using any other classes name it will be worked excellent.

Javascript output won't accept any CSS styling

I'm using simplecart.js which generates data for me to add to a cart, and then passes it to PayPal for me.
I have successfully added the 'add to basket' and 'checkout' features but am finding styling the JS-generated code impossible as no styles applied to it will work.
This is the code site has given to me, which generates a number of items such as name, quantity etc from stored data. It outputs all information correctly but any styles applied to the class names do nothing.
This is the code that generates the data:
<div class="simpleCart_items"></div>
This is the result from the web browser:
<div class="simpleCart_items"><div>
<div class="headerRow">
<div class="item-name">Name</div>
<div class="item-price">Price</div>
<div class="item-quantity">Qty</div>
<div class="item-remove"></div>
</div>
<div class="itemRow row-0 odd" id="cartItem_SCI-3">
<div class="item-name">The Jenny Snood £11</div>
<div class="item-price">£11.00</div>
<div class="item-quantity">1</div>
<div class="item-remove">
Remove
</div>
</div>
</div>
</div>
The browser is receiving all the data correctly, but applying any styles to the class names does nothing. For example, I have:
.headerRow{
background-colour:#0F0;
}
The result should be that the background of headerRow be lime, but nothing happens. It is not calling the style correctly.
I have tried everything but none of the classes will fetch the styles applied to them.
Here is a screenshot of how it looks, obviously not very nice unstyled, but I can't apply any styles at all to it.
Here is a link to the live site
A further examples:
I've added the code given which generates the totals:
<div class="simpleCart_total"></div>
I have tried giving it it's own new class and also styling the original, with !important - none of this works.
<div class="totals simpleCart_total"></div>
.simpleCart_total{
background-color:#0F0 !important;
}
.totals{
background-color:#0F0 !important;
}
None of the above seems to have any impact whatsoever.
There is some other css or inline javascript affecting the custom style your are attempting to use.
To mitigate this issue do one of the following:
Add !important after each css statement like so:
.headerRow{background-color:#0F0 !important;}
Reorder the css files so your custom css file is at the bottom
The problem here is that the styles are being applied dynamically by the js after your CSS (ie during the initialization of the plugin). You're only hope is to style it after this initialization with your own js, I think.
You can check this in Firebug... If you look at the elements there, you should see a bunch of inline styles being applied to them. These will trump your CSS in the header (and even the inline CSS you provide beforehand).
Edit: I saw some junky characters just before the directives in question (as well as those pointed out in another answer). I would try removing all the white space after the preceding directive and before the broken ones. It does not appear that the js is dynamically changing anything.

Categories