The Astro loop feature fails to include any spacing when dividing a title

Currently, I am working on creating a Title component that accepts a text prop. This text is then split using the text.split(" ") JavaScript method to create an array of words. The component loops over this array and displays each word within the heading tag passed to it. However, when the title is rendered through the loop, there is no spacing between the words. Oddly enough, manually placing divs inside the tag adds the necessary spacing. Is this normal behavior or am I overlooking something?

The components being utilized:

<Title
    Tag="h2"
    text="This is an example"
/>

Here is the component code with the loop included:

---
interface Props {
    Tag: string
    text: string
    class?: string
    line?: boolean
    highlight?: number[]
}

const { Tag, text, class: className, line, highlight } = Astro.props

const splitTitle = text.split(" ")
---

<Tag class:list={["c-title", className]}>
    {splitTitle.map((word, index) => <div>{word}</div>)}
</Tag>

<style is:global lang="scss">
    .c-title {
        --title-color: var(--scheme-contrast);

        color: var(--title-color);

        div {
            display: inline-block;
        }
    }
</style>

This currently renders as follows:

Thisisanexample

https://i.sstatic.net/GNway.png

On the other hand, the component without the loop looks like this:

---
interface Props {
    Tag: string
    text: string
    class?: string
    line?: boolean
    highlight?: number[]
}

const { Tag, text, class: className, line, highlight } = Astro.props

const splitTitle = text.split(" ")
---

<Tag class:list={["c-title", className]}>
    <div>This</div>
    <div>is</div>
    <div>an</div>
    <div>example</div>
</Tag>

<style is:global lang="scss">
    .c-title {
        --title-color: var(--scheme-contrast);

        color: var(--title-color);

        div {
            display: inline-block;
        }
    }
</style>

This version correctly renders as intended:

This is an example

https://i.sstatic.net/FCzsu.png

It should be noted that both methods result in the same DOM structure, so the differing behavior is perplexing.

Answer №1

<Tag class:list={["c-new-title", className]}>
    {
        splitTitle.map((word, index) => (
            <>
                <div>{word}</div>
            </>
        ))
    }
</Tag>

By introducing a fragment, the issue was resolved. This prevented the divs from being rendered stuck together.

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

divide the JSON object into distinct indexes

Below is an array containing JSON objects: items = [ { id: '1', name: 'Josh', transactionDate: '2012-08-10', creditAmount: '200', numberBank: '1234 ...

JavaScript regular expressions only recognize certain characters

When submitting a form, I need to validate a field and ensure that only specific characters are allowed. The permitted characters include: a-z A-Z 0-9 % . " ' & - @ # $ * / + = [ ] ! I attempted to use the following regex for validation: var r ...

Easily integrating a JavaScript file into an HTML document when utilizing a NodeJS Express server

Currently in the process of developing a chat application, utilizing the Express server with NodeJS and AngularJS for client-side management. Encountering an issue when attempting to include /js/code.js in my html, as it cannot be found due to not being p ...

JavaScript: Attempting to implement Highcharts without causing the browser to freeze

Is there a way to optimize loading multiple graphs without freezing the browser for too long? I want each graph to appear on the screen as soon as it's created, rather than waiting for all of them to finish rendering. I've tried using a similar ...

Incorporating data types into a constant in Typescript/Javascript

Imagine I wanted to ensure these variables are string objects by adding a type string declaration to this variable assignment. What is the correct way to accomplish this? const { someID, someName, someAPIenvironment } = useParams(); This is what I attemp ...

What is the best approach for testing a function containing document.querySelector() with unit tests?

export function calculateNavHeight() { const merchantNav = document.getElementById( 'merchant-header-main-wrapper-internal' ) const dw2Nav = document.querySelector('.cw_navbar__mainnav') let navHeight = 72 // Default Nav hei ...

Running React Boilerplate with forever is a great way to ensure your application stays

I plan on keeping the react-boilerplate application running indefinitely on the server. I recently came across forever, but I'm uncertain about how to pass parameters to it. The command to start the server looks like this: PORT=80 npm run start:produ ...

The array is not preserved by Mongoose once the .map(...) loop has ended

I'm encountering an issue where every time the Node.js quits the loop of .map(...), my Post.attachments array reverts back to the state of []. I'm curious as to why this behavior occurs. Below is the code snippet: req.files.map(async (file) => ...

Searching for the top 10 documents with the highest value in a specific field using mongoose

I am working with a mongoose model that includes a field called played_frequency. How can I retrieve the first 10 documents from all those available, based on the highest value in the play frequency? Here is the interface of my model: export interface ITr ...

Having problems getting my fixed header to work on my datatable. What could be the

Struggling to make my data table Thead sticky? I attempted using position: fixed;, top: 0; with CSS but it only worked in Firefox, not Chrome, Edge, or Opera. Here is an excerpt of my Ajax code: "stateSave": false, "orderCellsTop&quo ...

Package tracking static document within javascript module

I'm currently working on a project in parcel that involves three.js. It appears that I am having trouble loading a 3D model due to an incorrect path issue. My model is located in src/assets/models/mymodel.obj and I am attempting to use it within the ...

Tips for retrieving the responseText from an XMLHttpRequest within an express.router API function in Node.js

I’m struggling to figure out how to get my API function to return the XML response. I understand that XMLHttpRequest is asynchronous, and while I can log the response, I'm having trouble accessing it outside of the scope. How can I make sure that my ...

Tips for attaching the Bootstrap 5 dropdown menu to a particular element, especially when the dropdown element is contained within another element that has an overflow property set to hidden

I am utilizing the Bootstrap 5 dropdown menu within an owl-carousel. However, the dropdown is getting clipped because the outer div has an 'overflow:hidden' style in the owl-carousel. https://i.sstatic.net/YD9l2.jpg For the complete code snippe ...

How to use Angular ngRepeat to create multiple select fields that do not show previously selected data with ng-options

Looking at the issue from a high level; I'm fetching data from an api and creating a CRUD page for it. The user can choose from a set of labels provided in the data. Here is a code snippet illustrating my dilemma. The selected labels are denoted by t ...

What steps can be taken in Angular to eliminate an additional HTML tag created when using dynamic components with a structural directive?

I currently have a complex infrastructure within my project that includes: host component structural directive used in the host component's template (MyDir) another component used in the structural directive (MyComp) A simplified version is outline ...

Importing a MATLAB table file into a Node.js environment and converting it into an array

Currently in the process of setting up a test server for a Web-Application, where fake data needs to be transmitted via a Websocket. The fake data is stored in a MATLAB table file (.mat), which essentially consists of a 4000*192 array. My goal is to conver ...

What is the process for performing a redirection in Node JS?

I have been working on a task to redirect a page to the home page with the route '/search' upon form submission. Within my submit.html file, there is a form that utilizes the '/submit' post method to submit the form data when the submit ...

Achieving optimal hardware performance for WebGL compatibility is essential

Lately, I have been exploring the world of Three.js to create impressive 3D scenes in WebGL. To ensure compatibility for all users, I have also developed versions using Three's CanvasRenderer which may not be as detailed but can still function on brow ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

Iterate through the .json file and add markers to a leaflet map

Apologies for the basic question, but I'm struggling with understanding JavaScript and json files. I have a .json file that updates server object locations every 5 seconds, and I want to plot these coordinates on a map using leaflet for staff access. ...