Is it possible for me to create an If statement that can verify the current index within a Map?

I have the following TypeScript code snippet:

export default class SingleNews extends React.Component<INews, {}> {
    public render(): React.ReactElement<INews> {
        return (
            <>
                {this.props.featured
                    ? this.props.recentNews.map(post => (
                
                            <a
                                className={styles.singleNews}
                                href={post.link}
                                key={post.Title}
                            >
                                <div
                                    className={styles.singleNews__image}
                                    style={{ backgroundImage: `url(${post.image})` }}
                                />
                                <div className={styles.singleNews__content}>
                                <div className={styles.singleNews__content__info}>
                                <span className={styles.singleNews__content__info__label}>{post.Featured}</span>
                                <span className={styles.singleNews__content__info__date}>
                                            {post.date}
                                        </span></div>
                                </div>
                                <div className={styles.singleNews__content}>
                                    <div className={styles.singleNews__content__info}>
                                    
                                        <h2 className={styles.singleNews__content__info__title}>
                                            {post.Title}
                                        </h2>
                                    
                                        

                                        {post.likes ? (
                                            <div
                                                className={styles.singleNews__content__info__reactions}
                                            >
                                                <span
                                                    className={
                                                        styles.singleNews__content__info__reactions__likes
                                                    }
                                                >
                                                    <Icon iconName='Like' />
                                                    {post.likes}
                                                </span>
                                                <span>
                                                    <Icon iconName='ActionCenter' />
                                                    {post.coments}
                                                </span>
                                            </div>
                                        ) : null}
                                    </div>
                                </div>
                            </a>
                                                
                      ))

However, I want to dynamically render different HTML based on the current index. When I attempted to use an if statement inside the map function, I encountered an error stating "expression expected" on the if. Can anyone provide suggestions or advice?

Answer №1

The issue arises from using a statement as the body of your arrow function in this scenario.

Now that you need to include an if statement to check the index, you should utilize a block like so:

{this.props.featured
   ? this.props.recentNews.map((post,index) => {  
                if(index=0) { 
                  // add your logic here
                }
                return <a> .... </a>
     )}
}

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

Unable to present information retrieved from REST API, despite data being provided by the server

I'm attempting to make a REST call using a token in the header to retrieve information. To include the required header token, my code is structured as follows within my restClient.js, app.js, and users.js files. //restClient.js import { jsonServerR ...

Issue with PHP retrieving initial value of post data

Hi there, I am facing an issue with my PHP code where the first value of the input field is not being displayed. However, when I check the console.log, it shows correctly. Here is my console.log output: PHP Output: function summary() { $(document).re ...

Sending data to a PHP page to maintain state in an Angular application

Here is my current setup: In a dynamic Angular environment, I have various states connected to PHP pages. These PHP pages rely on specific data variables, typically provided as GET parameters outside of Angular. Now, I am looking for a way to switch to a ...

The JavaScript function getSelection is malfunctioning, whereas getElementById is functioning perfectly

I am encountering a peculiar situation while trying to input text into a textbox using a JavaScript command. The CSS locator does not seem to update the text, whereas the ID locator is able to do so. URL: Below are screenshots of the browser console disp ...

Exploring JSON objects in React for improved search functionality

Hey there! I'm working on implementing a search bar that updates the list of JSON entries based on user queries. Below is the code snippet that displays the video list (<Videos videos={this.state.data}/>). Initially, when the page loads, I have ...

Navigating array usage in Selenium IDE

I am trying to extract emails from a webpage using Selenium for future testing. I need to compare these emails with ones displayed in a selection later on. I attempted to read the emails within a while-loop but struggled with handling arrays in IDE. Unfor ...

Using ngTable within an AngularJS application

While working on my angularjs application, I encountered an issue with ngtable during the grunt build process. It seems that the references are missing, resulting in the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module pa ...

show an HTML webpage within a <div> container using AJAX technology

I am trying to include an HTML page named Introduction.html (located in the same folder as x.html) within div1. However, it does not seem to be loading properly. Below is a snippet of the code from x.html x.html <!DOCTYPE html> <h ...

Assigning properties to the constructor using `this.prop`

Within a React class component, I have multiple methods and the component receives various props. I am contemplating whether I should assign each prop as this.propName in the constructor and then access them using this.propName. For your reference, below ...

Make sure to always select the alternative option in ajax

I am trying to create a condition where if the value of id=type_investor is either 1 or 6, an email should be sent using a different controller. Here is my complete code: function (isConfirm) { if (!isConfirm) return; $.ajax({ ...

Utilizing AngularJS within a Captive Network Assistant (WISPr) on iOS and MacOS devices

In my past experiences with projects, it has been observed that Apple's Captive Network Assistant (also known as WISPr client) operates with a restricted browser. For further information, you can refer to How can I debug the browser in Captive Portal? ...

Error: Missing provider for MatBottomSheetRef

While experimenting in this StackBlitz, I encountered the following error message (even though the MatBottomSheetModule is imported): ERROR Error: StaticInjectorError(AppModule)[CountryCodeSelectComponent -> MatBottomSheetRef]: S ...

Issues with uploading files in NodeJs using express-fileupload are causing errors

I created a REST API in NodeJs for File Upload which is functioning correctly, however I am facing an issue. When I upload more than 2 images, only 2 or 3 get uploaded and sometimes one gets corrupted. I suspect that the loop is running too fast causing th ...

What is the process of using JavaScript code to read a text file?

Trying to use Google Charts while reading data from a text file. The code in JS is written for this purpose: function readTextFile(file){ var rawFile = new XMLHttpRequest(); rawFile.open("GET", file, false); // using synchronous call var allTe ...

Creating a Custom "Save As" Dialog in HTML5 and JavaScript for Downloading Files

I have developed a NodeJS/Express application that is capable of generating and downloading an Excel document (created using ExcelJS) when a user clicks on a button. Currently, the file gets automatically downloaded to the default download location of the ...

Error Message: Angular 5 with SignalR (DefinitelyTyped) - '$' Not Found in Typings

I am currently working on implementing SignalR into my Angular 5 application. To do this, I added the following TypeScript type definitions from DefinitelyTyped: npm install --save @types/jquery npm install --save @types/signalr The version of Typescrip ...

I am currently facing an issue with validating forms in JavaScript Document Object Model (DOM)

Whenever I click on a field and move to another one, the span tag turns red. Then, after pressing the submit button, an alert message pops up. However, if I turn the span red, fill in the field, and press the submit button, it shows success even if other f ...

Looking to set up an event handler for the browser's back button in next.js?

When my modal opens, it adds a hash to the URL like example.com/#modal. I want to be able to recognize when the back button is clicked in the browser so I can toggle the state of the modal. The challenge is that since I am using next.js (server-side rend ...

The use of `super` in Typescript is not returning the expected value

Trying to retrieve the name from the extended class is causing an error: Property 'name' does not exist on type 'Employee'. class Person { #name:string; getName(){ return this.#name; } constructor(name:string){ ...

What methods can be used to control access to document.styleSheets data, and what is the purpose behind doing so?

Recently, I came across the document.styleSheets API, which allows you to access stylesheets used by a website. Using this API is simple, for example, document.styleSheets[0].cssRules will provide all CSS rules for the first stylesheet on a page. When I t ...