How to refer static resource in Lightning component?

How to refer static resource in Lightning component?

I have a static component where the content is loaded dynamically as html. The lightning component provides some styles to present that content. I would like to provide icons, images that are defined as ‘Static Resources’ to that content from css. Like if there is a div with class ‘warningDiv’ then the css can be,

How can I dynamically load a static resource image in LWC?

For example a background image. const containerElement = this.template.querySelector (‘.container’); containerElement.style.backgroundImage = `url (‘$ {resourcePath}’)`; Obviously this is a hacky solution. It is error prone if static resources are misspelled but knowing there is a solution for dynamic resources makes me happy 🙂

How to reference a resource in a component?

To reference a specific resource in component markup, use $Resource.resourceName within an expression. resourceName is the Name of the static resource. In a managed package, the resource name must include the package namespace prefix, such as $Resource.yourNamespace__resourceName.

What should the name of a static resource be?

A static resource name can contain only underscores and alphanumeric characters, and must be unique in your org. It must begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores. namespace —If the static resource is in a managed package, this value is the namespace of the managed package.

How to use external stylesheet in Lightning component?

tag. The below example will showing you that how to use External styleSheet CSS in lightning component. this is div text with divStyle style class, which is come from external css file.

How do I add CSS to a lightning component?

This is the standard way to adding CSS for lightning components. You can add CSS to a lightning component bundle by clicking the STYLE button in the Developer Console sidebar. after click on the STYLE button on component bundle, new CSS file is create with .css ext.