Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app.

const LinkStyle = {
    textDecoration : 'none',
    color : 'rgba(58, 62, 65, 1)',
    '&:hover' : {
    backgroundColor : 'rgba(238, 240, 243, 1)'
    },
    mx : {lg : 2, md : 2, sm : 2, xs : 2},
}

I'm using it in my component like this:

<SomeDOMelememt style={({condition}) => condition ? LinkStyle : (LinkStyle) + 'border-radius : '20px''} />

Instead of creating a whole new object for the case when '!condition', I want to enhance the existing 'LinkStyle' object by adding some extra properties to cover both scenarios. I prefer not to create a separate object or add more conditional styling directly to <SomeDOMElement/>.

Answer №1

To selectively include a property in your styling, you can use conditional logic:

const LinkStyle = {
    textDecoration : 'none',
    color : 'rgba(58, 62, 65, 1)',
    '&:hover' : {
    backgroundColor : 'rgba(238, 240, 243, 1)'
    },
    mx : {lg : 2, md : 2, sm : 2, xs : 2},
    ...(condition && ({'border-radius' : '20px'}))
}
<SomeDOMelememt style={LinkStyle} />

Answer №2

To easily incorporate all keys from an object, utilize the spread operator ... in this manner:

<AnotherDOMelement 
  style={
    ({status}) => status ? ButtonStyle : {'background-color': 'red', ...ButtonStyle} />

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

Can someone please explain how I can implement a multi-submenu feature using JavaScript?

HTML CODES: <header> <nav> <ul> <li class="asmenu"><a href="#">Menu1 <i class="fa fa-caret-down"></i></a> <ul class="submenu deact ...

What is the best way to import the three.js OBJLoader library into a Nuxt.js project without encountering the error message "Cannot use import statement outside a module

Beginner here, seeking assistance. Operating System: Windows 10. Browser: Chrome. Framework: Nuxt with default configurations I have successfully installed three.js using npm (via gitbash) by running npm install three --save. It is included in the packag ...

Is it possible to efficiently transfer a Tensorflow.js Tensor between Node.js processes?

Currently, I am in the process of building an AI model using Tensorflow.js and Node.js. One of the challenges I am facing is handling a large dataset in a streaming manner due to its size being too massive to be stored in memory all at once. This task invo ...

Prevent repetitive content on your Node.js server

After realizing my small image hosting has many duplicate content, I am looking for a solution to prevent this issue in the future. My idea is to use either checksum or hash code so that whenever a new file is uploaded, it will be hashed and compared with ...

The JavaScript function for clearing an asp.net textbox is not functioning properly

I am working on an ASP.net project and have encountered an issue with two textboxes. When one textbox is clicked on, I want the other one to clear. Below is the code I have for the textboxes: <asp:TextBox runat="server" ID="box1" onfocus="clearBox2()" ...

What is the process for downloading a package from unpkg or adding an unpkg package to dependencies?

Challenge I attempted to install IPFS from the unpkg website. https://www.unpkg.com/browse/[email protected] / My Project This is a project built with React. Unfortunately, I am having trouble downloading this package or installing it in my packa ...

displaying date picker on button click with angular bootstrap ui

I am trying to display an AngularJS Bootstrap calendar only upon clicking a button, and I want to restrict it from appearing when clicking on the input field. Below is my code: <input type="text" onkeydown="return false;" ...

Is jQuery capable of appropriately escaping my quotes?

Currently, I am utilizing $.cookie() to retrieve all the values from a cookie which are stored in JSON format: var properties = $.cookie('params'); The output of properties is: {"distinct_id": "13f97d6600b42e-000e6293c-6b1b2e75-232800-13f97d66 ...

Having trouble retrieving values from the getEntry method in Contentful

How can I retrieve an entry from contentful using Contentful v10 with Node.js 18? I am having trouble accessing the value in getEntry(). interface Example { contentTypeId: 'item' fields:{ title: EntryFeildTypes.Text rate: EntryFeildType ...

Incorporate a new style into several previous slides using the Slick carousel feature

I'm attempting to utilize the Slick carousel to create a timeline. My goal is for the previous slides to remain colored as you progress through the timeline, and turn grey when you go back. I've tried using onAfterChange and onBeforeChange, but I ...

Is it possible to utilize material-ui's FloatingActionButton component as the submit and reset buttons for my redux-form?

Trying to implement a basic redux form with Material UI components. I've followed the example on their website and got the redux Field components to render as material-ui fields easily. However, I want to use material-ui buttons as my Submit and Rese ...

Does AngularJS have a feature similar to jQuery.active?

As I utilize selenium to conduct tests on my application, I am encountering numerous ajax calls that utilize $resource or $http. It would be convenient if there was a method in angular to monitor active ajax requests so that selenium could wait until they ...

Eliminating the use of undefined values in JavaScript output

When the following script is run in a JavaScript environment like Node.js, the output is as follows: undefined 0 1 2 3 4 The Script: for(var i=0;i<5;i++){ var a = function (i) { setTimeout(function () { console.log(i); ...

Tips for customizing and expanding a style object in reactjs

One of my challenges involves working with a base style object that looks like the example below: const baseGridStyle = { gridStyle: { '& .ag-header-row, .ag-filter-input:input': { fontSize: '14px', backgroundColo ...

Customizing input class in TextField with makeStyles

When attempting to override the padding property in a TextField input using MakeStyles, a new specific class named .makeStyles-input is generated and takes precedence over the MuiOutlinedInput-root class. Is there a way to add a property to the general in ...

What is the best way to extract a nested array of objects and merge them into the main array?

I've been working on a feature that involves grouping and ungrouping items. A few days ago, I posted this question: How can I group specific items within an object in the same array and delete them from the core array? where some helpful individuals ...

Transforming a detailed JSON structure into a more simplified format with Angular 2

As a newcomer to Angular 2, I find myself encountering a hurdle in filtering unnecessary data from a JSON object that is retrieved from a REST API. Below is an example of the JSON data I am working with: { "refDataId":{ "rdk":1, "refDataTy ...

What could be the reason for receiving an HttpErrorResponse when making a GET request that returns byte data

When using these headers, the API returns byte data as a response. let headers = { headers: new HttpHeaders({ 'Content-Type': 'application/octet-stream', 'responseType':'arraybuffer' as 'js ...

What is the best way to conceal the outline in a popup window?

I have successfully implemented a popup/modal window using JavaScript, but now I need to find a way to hide the outline map container. The initialization code for the map is as follows: self.mapDialogOptions = { autoOpen: false, m ...

The second parameter of the Ajax request is not defined

Having an issue with my Ajax request in Vue.js where the second parameter is logging as undefined in the console. I've been trying to fix this problem but haven't found a solution yet. This is the code snippet for $.ajax(): //$.ajax() to add ag ...