A guide to implementing the map function on Objects in Stencil

Passing data to a stencil component in index.html

<app-root
      data="{<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d4d7d6f5d2d8d4dcd99bd6dad8">[email protected]</a>, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f6929390b6919b979f9ad895999b">[email protected]</a>}"
</app-root>

Creating the App-root Stencil Component

import { Component, h, Prop } from "@stencil/core";

@Component({
  tag: "app-root",
  styleUrl: "app-root.css",
  shadow: true,
})
export class AppRoot {
  @Prop() data: [];
  
  render() {
    return (
      <div>
        {this.data.map(m => {
          return <div>
            <h1>{m}</h1>     
          </div>  
        })}
      </div>
    );
  }
}

Need help in displaying single data inside an h1 tag without it showing as undefined on the screen.

Answer №1

When using <app-root> in an HTML file (not TSX), you are limited to passing primitive types like string, number, and boolean. If you need to pass an array, you will have to manually parse it as outlined in this post about Stencil object properties not being set when provided through the HTML string.

The attribute value must be formatted as a valid JSON array (

["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e3e0e1c2e5efe3ebeeace1edef">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2145444761464c40484d0f424e4c">[email protected]</a>"]
)

In your specific scenario, instead of using JSON.parse, you could opt for passing a comma-separated list and creating an array with split(','). In this case, the attribute value should look like

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aacbc8c9eacdc7cbc3c684c9c5c7">[email protected]</a>,<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3155545771565c50585d1f525e5c">[email protected]</a>
.

Answer №2

In HTML, you are unable to set non-primitives as property values directly. However, you can achieve this using JavaScript:

<app-root></app-root>

<script>
  document.querySelector('app-root').data = ['<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a4b48496a4d474b434604494547">[email protected]</a>', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81e5e4e7c1e6ece0e8edafe2eeec">[email protected]</a>'];
</script>

It's important to note that

{<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4726252407202a262e2b6924282a">[email protected]</a>,<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afcbcac9efc8c2cec6c381ccc0c2">[email protected]</a>}
is not a valid array syntax in JavaScript/Typescript. Make sure to assign an empty array as the default value for your data property to prevent rendering issues if the data is not set (resulting in "undefined" displayed on screen).

@Prop() data = [];

To enhance the type of your prop, declare it as an array of strings:

@Prop() data: string[] = [];

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

Sending data through the backbone form?

Whenever the submit button is clicked, a post request should be made to the server with input data and it will return a JSON object. I am unsure where to define the success function and how to receive the response object. Is this the correct way to call a ...

Tips for defining a function without an arrow as a parameter

Understand that there may be individuals quick to flag this as a duplicate question, but trust me when I say that I have exhaustively searched on Google for almost an hour before turning to ask here. methods: { stylizeHeader: debounce(event => { ...

A highly effective method for nesting items within a list through recursive functions

I am currently in the process of developing my own commenting system because I have found that existing platforms like Disqus do not meet my specific needs. My backend is built using NodeJS and MongoDB, and I need to execute two primary queries on my data ...

The subsequent middleware in express next() is failing to trigger the next middleware within the .catch() block

I'm facing a puzzling issue with my POST route. It's responsible for creating transactions through Stripe using the Node package provided by Stripe. Everything works smoothly until an error occurs, such as when a card has insufficient funds. Whe ...

Utilizing YouTube API information with AngularJS

I am currently working on a project where I need to fetch all the playlists from a specific channel and then display the name of each playlist in my AngularJS application. var myApp = angular.module('app', ['ngResource']); myApp.facto ...

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

Horizontal navigation bar encroaching on slideshow graphics

I'm encountering difficulties aligning the horizontal menu below the image slider. When I have just an image without the slider, the menu aligns properly (vertically), but as soon as I introduce the code for the slider, the menu moves to the top and d ...

"Deleting a specific row from a SQL Server using Node.js: Step-by-Step Guide

Currently, my setup involves using nodeJs as the backend language and sql server as the database. While I have managed to delete whole table rows from the database successfully, I am facing a challenge when it comes to deleting a specific row. Here is the ...

Error message: App not defined in Ember App.router

Attempting to set up routing for my app for the first time, but struggling to grasp the logic. I managed to render my templates by adding the following code to my route.js file: import Ember from 'ember'; import config from './config/enviro ...

The issue with ngFileUpload causing empty file posts on Safari

Currently, I am utilizing ngFileUpload to transmit images to the Cloudinary service. My application is constructed on Ionic and is meant to be functional on both iOS and Android platforms. The code snippet below showcases my image uploading process: .se ...

Instructions for ordering this jQuery script that executes ajax and should return a 'true' value

In my javascript for form validation, I have added a new layer that calls an external function to send an Ajax request with the form validation results. The goal is to receive an email indicating whether the user passed or failed the validation. While cal ...

JavaScript client receives a response from the server

After filling out an HTML form and submitting it, the client validates the data (such as checking if the EULA checkbox is accepted) before sending it to the server. The server then checks the data and returns a status code. But how can I retrieve this stat ...

Using the fetch/await functions, objects are able to be created inside a loop

In my NEXTJS project, I am attempting to create an object that traverses all domains and their pages to build a structure containing the site name and page URL. This is required for dynamic paging within the getStaticPaths function. Despite what I believe ...

Is it possible to import a global package in Node if NODE_PATH is already configured?

Currently, I am encountering an issue with trying to import a globally installed package that is located at /some/path. To address this problem, I have configured NODE_PATH in my ~/.bash_profile and confirmed its existence by running 'echo $NODE_PATH& ...

How to create a fresh factory instance in Angular Js

I have implemented a factory in my application to retrieve a list of folders and display it on the front end. Additionally, I have a form on the front end where users can add new folders to the existing list. After adding a folder, I need to refresh my fac ...

Encountering issues with JavaScript/ajax if statement functionality

Driving me insane! Dealing with 2 modal forms - one for login and another for registration. Javascript handles client-side validation, followed by an ajax call to either a registration or login php file. The PHP files return 'OK' if successful or ...

What is preventing me from sending back an array of objects with an async function?

Working with node.js, my goal is to retrieve a list of bid and ask prices from a trading exchange website within an async function. While I can successfully log the object data using console.info() within the foreach statement on each iteration, when attem ...

What is the best way to use jQuery ajax to send various row identifiers when updating table data on another PHP page by selecting checkboxes?

When I select both of the green checkboxes, only the most recent table id is sent. The code below includes both the checkbox markup and jQuery function. Checkbox: <div class='md-checkbox has-success'> <input type='checkbox&apo ...

Show a pop-up window when a button is clicked, just before the page redirects

Is there a way to display a popup message before redirecting to another page when clicking on a button? Here's the scenario: <a href="addorder.php?id=<? echo $row01['id']; ?>" ><button id="myButton" class="btn btn-primary btn ...

Implement AngularJS to ensure that scripts are only loaded after the page has finished rendering

I am having trouble implementing the TripAdvisor widget on my website. It functions correctly when the page is refreshed, but it does not appear when navigating through links. Additionally, an error message is displayed stating that the document could not ...