Strategies for adjusting styled components according to state variables

I've been using styled components to customize my react application, and I'm trying to update the text color based on user selection. However, I'm having trouble seeing the changes reflected when passing the state in. Do I need to update using props instead? I tried reading through the documentation but ended up feeling even more confused. As a last resort, I decided to share the entire component here. Apologies if that's not allowed.

import React, {useState} from 'react'

import { pulse, flash} from 'react-animations'
import styled, { keyframes } from 'styled-components';
import Scan from './Components/Scan'
import Broke from './Components/Broke/Broke'
import Return from './Components/Return/Return'
import Forgot from './Components/Forgot/Forgot'
import { Button } from 'reactstrap';

const StartText =  styled.h1`
  font-size: 3em;
`
const Wrapper = styled.div `
  display: flex;
  justify-content: center;
`

const BrokeReason = styled.div `
  margin-top: 15px;
  margin-right: 5px;
  margin-left: 3px;
  border: solid #292b2c 2px;
  border-radius: 3px;
  background-color: #0275d8;
  font-size: 1.5em;
  padding: 5px;
  cursor: pointer;
  color: ${reason => reason.broke ? 'white' : 'red'}
`
const TotalWrap = styled.div `

`
const HeaderContainer = styled.div `
  display: flex;
  justify-content: center;
 
`
function App() {

const [reason, setReason] = useState({
    broke: false,
    forgot: false,
    return: false
})

const click = (event) => {
 
  if(event.currentTarget.textContent === 'I Broke My Chromebook'){

      setReason({...reason, broke: !reason.broke })
  } else if (event.currentTarget.textContent === 'I am returning my chromebook') {
    setReason({...reason, return: !reason.return })
  }else {
    setReason({...reason, forgot: !reason.forgot })
  }
}

  return (
    <TotalWrap>
    
      <HeaderContainer>
      <h1>Select your problem</h1>
      </HeaderContainer>
    <Wrapper>
    <BrokeReason onClick={click}>I Broke My Chromebook</BrokeReason>
    <BrokeReason onClick={click}>I am returning my chromebook</BrokeReason>
    <BrokeReason onClick={click}>I Forgot my chromebook</BrokeReason>
    </Wrapper>
    {/* <Scan /> */}
    {reason.broke ? <Broke style={{backgroundColor: 'red'}}/> : null || reason.return ? <Return /> : null || reason.forgot ? <Forgot /> : null}
  
    </TotalWrap>
  );
}

export default App;

Answer №1

Utilizing string interpolation (template literals), a styled component incorporates a function that accepts the props of the component as its initial parameter. This allows for customization within the component, as demonstrated below:

const StyledBox = styled.div `
  margin-top: 15px;
  margin-right: 5px;
  margin-left: 3px;
  border: solid #292b2c 2px;
  border-radius: 3px;
  background-color: #0275d8;
  font-size: 1.5em;
  padding: 5px;
  cursor: pointer;
  color: ${props => props.active ? 'white' : 'red'}
`

To implement this functionality, simply pass the desired value to the props:

<StyledBox active={isActive}>

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

Utilize Google Maps geocoding functionality to pinpoint a location and then

I've encountered this strange phenomenon, but first let's take a look at the code: HTML <div ng-app='maptesting'> <div ng-controller="MapCtrl"> <div id="map_canvas" ui-map="myMap" style ...

[filepond] in order to enroll using the serverId value received from the server

Using 'filepond' within a Vue application is causing an issue. In the "process" function, the ID value obtained after transferring the file to the server (response.id) needs to be registered as 'serverId' of the file. Upon checking the ...

Monitoring transactions through interactive buttons that lead to external destinations

Tracking purchases on my website using a dynamic button that redirects to other sites is essential. See the code snippet below: <div class="buyproduct"> <a onclick="target='_blank'" href="<?php echo $this->product['from&apos ...

Acquiring JSON data nested within another JSON object in D3

After looking at this reference, I am attempting to integrate similar JSON data into my webpage. The challenge I am facing is that my JSON contains nested JSON. Here is an example of how my JSON structure looks: { "nodes": [ {"fixed":true,"classes": null, ...

Setting up React Native on a Mac M1 device

I am currently setting up React Native on my MacBook M1 Despite having installed npm, JDK, Node, Rosetta, CocoaPod, VSCode, Android Studio, Xcode and more, when I try to run the command (npm start), the directories for iOS and Android are not present. The ...

Should values be passed as parameters from the component to the state, or should the status be accessed directly in the action creator

Within my project, I am faced with the dilemma of how to handle an action creator that relies on values stored in the application's state. The question at hand is determining the most effective approach to take. Initially, two possible solutions come ...

What is the best way to achieve consistent alignment in Javascript?

I have been attempting to incorporate HTML code within JavaScript for alignment and styling. Despite searching on Google for 3 to 4 days, I have not found a suitable answer yet. What exactly am I looking for? Here is a snippet of my JavaScript code: funct ...

The error message keeps appearing consistently. What is the best way to manage this error?

Even after entering the data in this field, it was supposed to disappear. However, that didn't happen as expected. <md-input-container class="md-block" flex-gt-sm> <label>Budget</label> <input name="budget" ng-model="newTri ...

Tips for estimating a value within a dataset using JavaScript

The Main Idea My inquiry revolves around the concept of predicting values from a dataset using JavaScript. To better illustrate my issue, I will provide an example of the desired outcome. If you are familiar with Mathematica, you may be aware of the Pred ...

No reply received on the web browser

I have written a code that is intended to read a JSON file and display it in the browser. The code is functioning correctly as it prints the data to the console, but for some reason, the data is not displaying on the browser. app.post("/uploadfile&q ...

AngularJS consistently leaves a blank element within a select tag

I am a newcomer to Angular.js and this forum, and I am keen on trying out some basic concepts. However, I hit a roadblock while working with select and options elements. In my small app, I aim to incorporate a select box, but I keep seeing a blank option ...

Retrieve specific values from columns for dynamically generated rows using JavaScript

Currently, I am in the process of creating a dynamic table using PHP. In my screenshot, there are two rows with multiple columns. Each column in both rows has the same id. For example, the column for Monday has id="mon" in the first row and also id="mon" i ...

Installing different versions of a package in npm can be done by loading multiple versions

I am in the process of setting up a web API and I want to provide support for various versions of the underlying library. In essence, I would like to access it through: where x.y.z represents the version of the library I am utilizing. Using npm for mana ...

Is there a way for me to isolate the words that conclude with a number?

After receiving information from the back-end, I am required to convert it into multiple words and store them in an array. How can I achieve this using regular expressions? Here are the words: Enter Room/Area^_^Area 100#_#Enter Grid^_^Grid2#_#Enter Level ...

A step-by-step guide on linking Threejs with React

I am currently utilizing React and a canvas. I am interested in transitioning the canvas to WebGL using the Three.js library. Can someone provide guidance on how to integrate this library with React? For example, I have the following element: <div ref= ...

CSS: Alignment of Lists with Three Items

In my CSS, I am aligning two parts of a list item to the left and right side like this: ul li div.left { float: left; } ul li { text-align: right; } <ul> <li><div class="left">On the left</div>On the right</li> ...

Changing the rotation of an object in THREE.js to match Canvas rotation

Hello amazing minds of stackoverflow. I am in the process of converting three js mesh positions to html5 canvas positions. While I have successfully converted vector3 position to canvas position, I am facing difficulties with converting mesh rotation to ca ...

Achieve consistent card body heights in Bootstrap 4 with the card group feature

I am working towards achieving a specific layout using Bootstrap 4's card-group feature, as shown in the image below: The goal is to have everything at the same height within each card (including card-header, card-title, and small subtext if present) ...

Employing an angular ng-model expression

Inside a controller: $scope.bar = {'label': 'user_label', 'bindTo': 'user.name'}; Next, in the HTML: <label for="user_label">User Label</label> <input name="{{bar.label}}" type="text" class="form-co ...

Will JavaScript modules be executed just once upon importing them?

When a module A is imported inside both module B and C, will the code inside A be executed 2 times in total? For example, if I invoke fetch() within A, will fetch() run twice? Here's an illustration: //file: A.js var A = { init: false, count: 0 } ...