Updating the design attributes of a div by utilizing ReactJS hooks upon clicking

Among my collection of elements with distinct IDs and a common className, I aim to modify the background, text color, and font when a user interacts with them.

To achieve this, I defined two variables (Style1 and Style2) to represent the styles for normal and clicked elements respectively. Style1 applies to the clicked element.

const tileStyle1: CSS.Properties = {
    backgroundColor: 'blue',
    fontFamily: 'londrinaBlackRegular',
    color: 'yellow',
  };  

  const tileStyle2: CSS.Properties = {
    fontFamily: 'londrinaSketcheRegular'
}; 

I also established a third variable named tileStyle which is integrated into the HTML structure of all elements. For instance:

<div className="linkcontainer" ID="Tile3" style={tileStyle} onClick={handleClick}>Marketing</div>

<div className="linkcontainer" ID="Tile4" style={tileStyle} onClick={handleClick}>Support</div>

Initially, I tried using a ternary operator to assign tileStyle dynamically to each element:

{clickedTile === "Tile3" ? tileStyle = tileStyle1 : tileStyle = tileStyle2;}
<div className="linkcontainer" ID="Tile3" style={tileStyle} onClick={handleClick}>Support</div>

{clickedTile === "Tile4" ? tileStyle = tileStyle1 : tileStyle = tileStyle2;}

<div className="linkcontainer" ID="Tile4" style={tileStyle} onClick={handleClick}>Support</div>

Unfortunately, it seems that these are not standard objects, leading to a significant error message: Objects are not valid as a React child (found: object with keys {fontFamily})...

Answer №1

A variable assignment cannot be included in the return method in React because it will attempt to render it. However, you can assign variables while setting the styles prop itself, where you incorporate your ternary expression (since code inside {} is treated as regular JS expression), and then return a dictionary.

<div className="linkcontainer" ID="Tile3" style={clickedTile === "Tile3" ? tileStyle1 : tileStyle2} onClick={handleClick}>Support</div>

<div className="linkcontainer" ID="Tile4" style={clickedTile === "Tile4" ? tileStyle1 : tileStyle2} onClick={handleClick}>Support</div>

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

Trouble with Loading Google Place Autocomplete API in HTML

I utilized the Google MAP Place Autocomplete API for a web project. Click here to view the code and output. <form> <input id="origin-input" type="text" class="form-control" placeholder="From"/> <br/> <input id="de ...

Update the menu-link class to active for a single-page website

Currently, I have a one-page website that serves as a portfolio. The website features a menu at the top with links that direct visitors to specific sections of the page using # as links. I am looking to enhance the user experience by implementing a functi ...

Clicking the button does not result in the conditional card being displayed in the content material user interface

Check out my code here. The objective is to display the Login card when clicking on the "Login" button, and show the Register card when clicking on the "Register" button. I tested this functionality using the following code: import React,{useState} from ...

Modify the input value when using the get_search_form() function in Wordpress

After experimenting with the latest get_search_form() function in WordPress, I've encountered an issue where I can't figure out how to remove the text label from the search submit button. Does anyone have any suggestions or solutions for this pr ...

How to fix React useContext not triggering a rerender when state changes

I am completely new to working with React, so I apologize in advance if my question is too basic. Despite searching extensively, I couldn't find a solution anywhere. My query pertains to the ExtensionsContext component, which stores an array of Exten ...

Having trouble with NPM's global command installation due to a proxy issue?

Hey, I recently installed Node JS version 10 and Npm version 6 on my system. When I attempt to run the command npm install -g yarn I encounter an error message https://i.sstatic.net/XIP4x.png To troubleshoot, I searched for commands to add a proxy: np ...

Is there a way to control a single Angular application using multiple JavaScript scripts?

Summary: I am looking for a way to allow two script files to handle different tasks within the same angular app. One needs to initialize the app, while the other needs to assign a templateCache object to a section of JSON stored in localStorage. Backgrou ...

"Utilize an HTML file open dialog box to gain access to the server's

Is it feasible to implement a file open dialog box that displays files and directories from the server's file system? In my web application, there is a need for users to select a file that resides on the server. Are there any plugins available for th ...

Loading Ajax content into div (Wordpress) without pre-loading the font can cause display issues

Currently, I'm implementing a JavaScript function within Wordpress using Ajax to load the content of a post into a modal div when specific elements are clicked. Here is an example of how the JS function appears: function openProjectModal($that) { ...

Convert JSON data into an HTML table with custom styling

If you have a set of JSON data that you want to convert into an HTML table, you can use the following code: $.each(data, function(key, val) { var tr=$('<tr></tr>'); $.each(val, function(k, v){ $('<td>' ...

Eliminating Google Adsense from Blog Posts

In each of my posts, I manually insert one Adsense unit. Here is the code: <div id="toppostad" style="float: left"> Adsense code </div> Initially, I assigned an id to the div when placing the code with the intention of using display:none; to ...

Could someone lend a hand in getting the X to align properly on this div? I've been struggling with it for ages and just can't seem to crack

This is a demonstration of the CodePen project: Click here to view <div class="annotation"> <div class="annotext"> <div class=annobar></div> <div class="x">✕</div> Lorem ipsum dolor sit amet, consectetur adipiscing e ...

Store information in an array for a permanent solution, not just a temporary one

When adding entries to a knowledgebase using the following code, I encounter an issue where the entries are only available during the current session. Upon reloading the site, the entries are lost. Can you help me troubleshoot this problem? Here is a snip ...

Having trouble with the .d.ts module for images?

I'm relatively new to Typescript and the only thing that's giving me trouble is the tsconfig.json. My issue revolves around importing images (in Reactjs) and them not being found: client/app/Reports/View.tsx:11:30 - error TS2307: Cannot find mod ...

Is it possible to extract individual values from the outcome of an SWR query using destructuring?

I'm encountering a simple issue with calling an external API: const fetcher = (...args) => fetch(...args).then(x=>x.json()) const {data:{results}, error} = useSWR("https://xxxxxxxxxxxxxxxx",fetcher) Every time I attempt to destructu ...

Are there any potential performance implications to passing an anonymous function as a prop?

Is it true that both anonymous functions and normal functions are recreated on every render? Since components are functions, is it necessary to recreate all functions every time they are called? And does using a normal function offer any performance improv ...

Using Bootstrap 4 to create a modal that is triggered remotely

I am facing an issue with the Modal in remote mode after updating to the latest version of Twitter Bootstrap, which is Bootstrap 4 alpha. While it was working perfectly fine with Bootstrap 3, I now encounter a problem where the popup window appears but the ...

How can you automatically sign in another tab in react js when one tab is already logged in?

Whenever I log into one tab in ReactJS, I find myself needing to log into the other tabs simultaneously as well. ...

Tips for encoding a base64 string into formats such as PDF, doc, xls, and png using jQuery, JavaScript, and HTML5

Need help handling base64 strings received from the server to save files in multiple browsers (IE, FF, Chrome). If receiving a PDF base64 string, how can it be saved in the browser? Also, if receiving an Image or Doc base64 string, what is the process fo ...

Remove and refresh the user's JWT token in the browser's local storage using a single command

I've implemented a component that allows users to update their details by essentially deleting and recreating their account using Redux and JWT. It's working well for me at the moment, but if there's a better approach I'd be open to sug ...