`How can we efficiently transfer style props to child components?`

Is there a way to pass Props in the Style so that each component has a unique background image?

Take a look at this component:

countries.astro

---
import type { Props } from 'astro';
const { country, description } = Astro.props as Props;
---

<section>
    <div>
        <h1>{country}</h1>
        <p>{description}</p>
    </div>
</section>

<style>
    section {
        height: 100vh;
        color: #fff;
    }

    div {
        height: 100%;
        width: 40%;
        padding: 0 5% 0 10%;
        display: flex;
        flex-direction: column;
        justify-content: center;

    }

    h1 {
        font-size: 8rem;
    }
</style>

Now, if you want to have different background images based on the country in the index file:

index.astro


---
import Countries from "../components/Countries.astro";

import Layout from "../layouts/Layout.astro";
---

<Layout title="Countries">
    <Countries country="ITALY"/>
    <Countries country="SPAIN"/>
    <Countries country="GERMANY"/>
</Layout>

<style>

</style>

If you have any suggestions on how to achieve this, please let me know!

Thank you!

Answer №1

If you want to customize the background images for the Countries components in your index.astro file according to the country, one way to do it is by passing a style prop to the Countries component and utilizing conditional CSS classes. Here's how you can implement this functionality:

  1. Update your Countries.astro component to accept a style prop that determines the background image:
---
import type { Props } from 'astro';
const { country, description, style } = Astro.props as Props;
---

<section class={`country-section ${style}`}>
    <div>
        <h1>{country}</h1>
        <p>{description}</p>
    </div>
</section>

<style>
    section.country-section {
        height: 100vh;
        color: #fff;
    }

    /* Define different background images for each country based on the provided style prop */
    section.country-section.italy {
        background-image: url('italy.jpg');
    }

    section.country-section.spain {
        background-image: url('spain.jpg');
    }

    section.country-section.germany {
        background-image: url('germany.jpg');
    }

    /* Add more country-specific styles here if needed */
    
    div {
        height: 100%;
        width: 40%;
        padding: 0 5% 0 10%;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    h1 {
        font-size: 8rem;
    }
</style>
  1. In your index.astro, assign the appropriate style prop to each Countries component based on the country:
---
import Countries from "../components/Countries.astro";
import Layout from "../layouts/Layout.astro";
---

<Layout title="Countries">
    <Countries country="ITALY" style="italy" />
    <Countries country="SPAIN" style="spain" />
    <Countries country="GERMANY" style="germany" />
</Layout>

<style>
    /* You can define any global styles for your index page here if necessary */
</style>

By passing the style prop to each Countries component and incorporating conditional CSS classes in the Countries.astro component, you are able to apply distinct background images for each country section. The CSS defines these specific images corresponding to the style prop values assigned in the index.

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

AngularJS File Input element triggering only once when selecting the same file

I have created an Angular directive to customize the file upload input. directive('ngFile', function () { return { link: function (scope, element, attrs) { var button = element.find('button[data-fileInputButton]&apos ...

Choose the property category

Is there a more efficient way to specify the type of a property in TypeScript without resorting to casting? Take a look at this example: interface Overlay { type: "modal" | "drawer" other?: number } const rec = { obj1: { ty ...

Loading CSS files conditionally in Angular2's index.html

Currently, my index.html page features a dark theme: <base href="/"> <html> <head> <title>XXX</title> </head> <body> <link rel="stylesheet" type="text/css" href="assets/dark_room.css"> <my-app ...

Looking for a demonstration using dust.js or handlebars.js in a two-page format with express3.x and node?

Currently, I am in the process of selecting a templating engine to use. While I have come across numerous single-page examples utilizing template engines, I am specifically searching for a practical example that demonstrates handling two distinct pages whi ...

I am struggling to figure out how to make the responsive menu close

#switch image var up = 'https://image.flaticon.com/icons/svg/149/149187.svg'; var down = 'https://image.flaticon.com/icons/svg/128/128397.svg'; $('#resNavToggle').click(function() { if ($('.resNavIcon').attr( ...

What is the process for triggering a function event on click (or any other function) within a browser's activation?

Some time ago, I was trying to figure out why the onclick event wasn't working when I clicked on a specific area of the browser. After consulting a guide, I discovered the issue and fixed it. It turns out that the problem was quite simple, and now I u ...

Ideal JavaScript data structure for connecting three arrays

My goal is to establish a connection between three arrays in the following manner: arr1 = ['A', 'A', 'B', 'B', 'C', 'C' 'A', 'C'] arr2 = ['a', 'aa', ' ...

What is the best way to retrieve the value of a dynamically created button in code?

I am dealing with a situation where I have a button that is supposed to fetch some data based on the classroom ID. button(type='button' id='getButton', onclick='get()', value=classroom.id ) Class Students Additionally, I ha ...

Creating a service class instance within an interceptor in NestJS

When working with interceptors in NestJS (view documentation), I encountered a situation where I needed to call a service within the interceptor. Here is the approach I took: export class HttpInterceptor implements NestInterceptor { constructor(privat ...

Issue with margins of sections when attempting to activate menu class while scrolling

My Objective: I want to create a website where the menu highlights the section that is currently being viewed as the user scrolls up and down. Progress So Far: I have successfully implemented a functioning menu that changes to "active" when the correspo ...

Ways to invoke a prop function from the setup method in Vue 3

I encountered the following code: HTML: <p @click="changeForm">Iniciar sesion</p> JS export default { name: "Register", props: { changeForm: Function, }, setup() { //How do I invoke the props change ...

Upon upgrading @types/angular, I encountered error TS2694 stating that the namespace 'angular' does not have an exported member 'xxx'

Following the upgrade of angular and @types/angular to version 1.6.x, an array of TS2694 errors suddenly appeared: error TS2694: Namespace 'angular' does not include an exported member named 'material' error TS2694: Namespace 'ang ...

Exploring the dynamics of Kendo UI's MVVM approach using J

Is there a way to make an ajax call in Kendo without involving the grid? I am new to Kendo and struggling to populate a span element with data fetched from one of my controller methods. The data is present as I can see it in the alert message, but it' ...

Using VueLoaderPlugin() results in an 'undefined error for 'findIndex' function

Currently, I am in the process of integrating a Vue CLI app into another web project that we are actively developing. The Vue app functions without any issues when utilizing the development server bundled with Vue CLI. Due to the presence of .vue files wi ...

Error: The value of 'id' cannot be assigned to an undefined property

Recently, I've been delving into learning JS Express and decided to create a basic solution to handle GET / DELETE / POST / PUT requests. Everything was running smoothly until I encountered an issue with the POST router. Below is the code snippet for ...

Are Ajax Caching and Proper Format Being Employed?

Can you help me with a JavaScript event that I have to call in this way: function addEvent(date, resId) { $("#appPlaceholder").load("/Schedule/Add?date=" + date.format()+"&resourceId="+resId, function () { $('#event ...

Generate a div element dynamically when an option is selected using AngularJS

I'm having trouble dynamically creating div elements based on the selected option value, but for some reason ng-repeat isn't working as expected. Can you help me figure out what I'm missing? Here's the HTML snippet I'm using - &l ...

Dealing with Typescript Errors in Ionic3: How to Handle "Property 'x' does not exist on value of type 'y'" Issues

I stumbled upon this particular post (and also this one) while searching for a solution to my issue. I am looking to suppress these specific errors: 'Payload' property is missing from the 'Matatu' type. 'Key' property is no ...

Unable to Define Headers in Fetch GET Call

My current struggle involves sending a GET Request from the browser to my backend (which uses node + express). However, I am encountering issues with setting the headers properly. Below is the code snippet from the frontend: let accessToken = localStorage ...

Issues with the orderBy function are causing unexpected behavior

After creating 3 groups - priority 1, 2, and 3 with orderBy:priorty for each pushed task to go into their designated group, I noticed some strange behavior within the groups where they don't sort properly when more data is added. <input ng-model=" ...