When we find ourselves within a fat arrow function

I'm struggling with this code. I have a ternary operator within a fat arrow function, but for some reason it's not working. There are no errors in browserify or the console, but the headers are not being printed.

If I remove the {} and ternary operator, everything works as expected.

What am I missing here?

<Row className="grid-header">
    {
        this.props.columnsInfo.map((info) => {
            width = (info.colWidth) ? "className={info.colWidth}" : "xs={this.calculateColumnSize()}";
            <Col style={{ paddingTop: 10, paddingLeft: 10 }} key={info.header} width>{info.header}</Col>
        })
    }
</Row>

Answer №1

Don't forget to include the return statement within the map() function.
Within the map(), each iteration should return a value, otherwise it will be ignored during rendering.
When using a fat arrow function with "{}", you need to explicitly use the return keyword like this: ((x) => {return x + x}) for variables, while without "{}" there is an implicit return like this: ((x) => x + x).

Solution

<Row className="grid-header">
    {
        this.props.columnsInfo.map(info => {
            const width = info.colWidth 
              ? "className={info.colWidth}"
              : "xs={this.calculateColumnSize()}";
            return <Col style={{ paddingTop: 10, paddingLeft: 10 }} key={info.header} width>{info.header}</Col>
        })
    }
</Row>

Answer №2

Make sure to explicitly return the JSX if it's not the entire body of the fat arrow function.

Here is your updated code:

<Row className="grid-header">
    {this.props.columnsInfo.map(info => {
            const width = (info.colWidth)? "className={info.colWidth}" : "xs={this.calculateColumnSize()}";
            return (<Col style={{paddingTop:10,paddingLeft:10}} key={info.header} width>{info.header}</Col>);
    })}
</Row>

The reason why it works when you remove the curly braces and ternary operator is because a fat arrow function, without curly braces for the body, implicitly returns the body which should be only one statement. Adding a second statement in the function body requires curly braces, and since there are now curly braces, you need to use the return keyword to explicitly return your JSX line.

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

Converting a String to an Integer in JavaScript

I'm having trouble printing the sum in this code // 1. create variables // 2. input numbers into variables [but they are strings] // 3. unable to print the sum // Variables let num = [""]; let num22 = [""]; // Add new number to num ...

How do I utilize Ajax to compare the value selected from a drop down menu in a form with entries in my database, and retrieve the corresponding record/row to automatically fill in a form?

I have a drop-down menu where users can select an option. I need to match the selected value with the corresponding record in my database under the "invoiceid" column, and then populate a form with the associated data when a prefill button is clicked. Belo ...

Tips for preventing the initiation of a session on a specific Express route?

Currently, I rely on ExpressJS as my app framework and also utilize connect-memcached for managing sessions within Express. app.use( express.session({ secret: "blah blah", store: new MemcachedStore({ ... }) })); This setup has been very effective. Ho ...

I need assistance setting up a Facebook page feed using Angular.js. I want to display the posts in a list of cards and include a fullscreen image gallery. Is

Hey there! I'm in the process of developing an app that pulls Facebook page posts and showcases them with custom CSS. The app is functioning smoothly with two controllers, DashCtrl and MainCtrl, each working fine on its own. However, when trying to tr ...

React Redux components are failing to render after changes are made to the state array

I'm fairly new to using React, Redux, and Thunk in my project. Right now, I'm facing an issue where I fetch an array from an API call in my action/reducer, but it doesn't re-render in the connected component/container that's hooked up t ...

Using VueJS Computed Property along with Lodash Debounce

I have been encountering a slowdown while filtering through a large array of items based on user input. I decided to implement Lodash debounce to address this issue, but unfortunately, it doesn't seem to be having any effect. Below is the HTML search ...

AngularJS Cascading Dropdowns for Enhanced User Experience

There is a merchant with multiple branches. When I select a merchant, I want another dropdown list to display the data from merchant.branches. The following code does not seem to be fixing the issue: <label>Merchant:</label> <select ng-if= ...

Guide to encapsulating a container within a map function using a condition in JSX and TypeScript

Currently, I am working with an array of objects that are being processed by a .map() function. Within this process, I have a specific condition in mind - if the index of the object is greater than 1, it should be enclosed within a div element with a parti ...

Personalized parameters in communication for Quickblox's JavaScript

Sending a chat message with custom parameters to the Quickblox API involves specifying various details such as the body of the message, date sent, dialog ID, and more. For example: message: { body: 'something', date_sent: 'some date&apo ...

Is it possible to refactor this forwardRef so that it can be easily reused in a function?

Currently, I am in the process of transitioning my application to Material UI V4 and facing challenges with moving my react router Link components into forwardRef wrapped components when setting the 'to' prop programmatically. The code below doe ...

NodeJS with Selenium - Attempting to Choose a Button

The HTML <button class="RCK Hsu USg adn gn8 L4E kVc iyn S9z Vxj aZc Zr3 hA- Il7 hNT BG7" tabindex="0" type="submit"> <div class="KS5 hs0 mQ8 un8 tkf TB_"> <div class="xuA"> ...

Tracking user session duration on a React Native app can be achieved by implementing a feature that monitors and

I'm currently focusing on tracking the amount of time a user spends on the app in minutes and hours, and displaying this information. I have successfully implemented the functionality to count minutes, but I am struggling to figure out how to track wh ...

Is there a way to ensure my chat view functions properly without relying on partial views?

I am currently working on integrating a private chat feature using SignalR in my project, and I have encountered an issue while creating a View with accessible model values to pass to the server. Specifically, I have a list of doctors, and when a user clic ...

Issue arises after injecting HTML element into the DOM due to memory constraints and display inconsistencies

Upon executing the following script in Firefox... var d = $("<div class='test'></div>"); d.hide(); $("body").prepend(d); d.show(); ...and examining the HTML, the inserted element will have the style attribute: style="display: blo ...

Azure experiencing issue with MUI Datepicker where selected date is shifted by one day

I have developed a unique custom date selection component that utilizes Material UI and Formik. This component passes the selected date value to a parent form component in the following manner: import React from 'react'; import { useField } from ...

Create an interactive mechanism where one scrollbar dynamically adjusts another scrollbar and vice versa

Using the provided js-bin, how can I synchronize scrolling between the "left" div and the "right" div when using the mouse wheel? Currently, if you uncomment the code block, the scrolling behavior changes from scrolling by 100px per scroll to scrolling pi ...

Creating an asynchronous function in Node.js that returns a promise, but experiencing unexpected behavior when using console.log to display the result

Recently, I created a simple and compact API that determines the gender of a person. It functions by sending a get-request to a specific page which responds with a JSON object. This snippet illustrates how my module works: 'use strict'; const ht ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Changing a string-stored array into a List object in JavaString

Here is a messy nested list that I need to convert into a list of numbers: nested_list = [ ["[63]"], ["[61]"], ["[7]"], ["[63]"], ["[80, 18]"], ["[80, 43, 18, 20]"] ] I know it's ...

Remove the background color from a semi-transparent circular CSS div when it is being dragged

My circular div is being dragged for a drag and drop operation, but there's always a translucent square around it. How can I remove this unwanted effect? body{ background : #BBD1DF; } .dragdemo { width: 170px; height: 170px; line-hei ...