Getting style information from a parent element in ReactJS involves accessing the parent component's CSS properties

Is there a way to automatically change the color of text inside a button component based on the color of the button itself? I'm trying to access the parent element's color in my text component. Here's what I have:

const MyText = (props) => {
  const ref = useRef<HTMLElement | null>(null);

  useEffect(() => {
    const styles = window.getComputedStyle(ref.current).getPropertyValue('color');  //test
  }, [ref]);

  return <MyTextStyled ref={ref} {...props} />;   // styled components 
};

const MyPage = () => {
  return (
   <Button> // my button styled components
     <MyText>Button 1</MyText>
   </Button>
  );
};

How can I extract the button background color to dynamically change the text color? Currently, I only have access to the text styles and not the parent element's styles.

Answer №1

Including custom CSS to the text area: color: 'inherit'

Answer №2

To fix the issue, set the color state in the parent component and then pass it down to both child components. Make sure to also pass down a function to change the color. Here is an example:

Check out the code snippet below:

const MyText = (props) => {
  const ref = useRef<HTMLElement | null>(null);

  useEffect(() => {
    const styles = props.color;  
  }, [props.color]);

  return <MyTextStyled ref={ref} {...props} />;   
};

const MyPage = () => {
  const [color, setColor] = useState('blue')
  return (
   <Button color={color} setColor={setColor}> 
     <MyText color={color}>Button 1</MyText>
   </Button>
  );
};

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

Creating a loop in a column-based carousel without using JavaScript

I'm currently working on developing a carousel using JavaScript or jQuery. I've attempted the code snippet below, but I'm having trouble getting it to display in 3 or 4 columns. While I understand that Bootstrap can handle this easily, I&apo ...

Is there a way to attach a file in Mongoose Schema? I tried using String and it worked, but when I tried to use File, I encountered the error "[1]Error: File is not

const mongoose = require('mongoose'); const { Schema } = mongoose; const NoteSchema = new Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'user', }, title: { type: String, required: true, }, attac ...

Error occurred while trying to launch React application with "npm start" command due to ELIFECYCLE issue

Encountering an error while attempting to launch my React app. events.js:174 throw er; // Unhandled 'error' event ^ Error: spawn powershell.exe ENOENT at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19) ...

Guide on converting enums in Angular 6

I have been working on translating enums in Angular, but I'm facing a challenge. While I can read and display them in a dropdown menu, translating them is proving to be difficult. Here is an example of my code: export enum test { test1 = '1 - ...

Encountering an error in Strapi project: URL undefined

I am currently in the process of setting up a Strapi application and getting it up and running. Following the instructions provided in this document: After successfully setting up Strapi and creating the application, I encountered an error when trying to ...

Designing a personalized user template for a feature in Angular 2

My component currently has a default template: import {Component} from 'angular2/core'; @Component({ selector: 'my-component', template: ` <div class="container"> ...

Trouble with altering the background color of AppBar in React MUI V5

import React from "react"; import { AppBar, Toolbar, Grid, IconButton, InputBase, Badge, } from "@mui/material"; import { ChatBubbleOutline, NotificationsNone, PowerSettingsNew, } from "@mui/icons-material"; ...

Blending of Typescript Tuples

Is there a way to merge tuples in TypeScript such that one tuple is added at the end of another? Here is an example: type MergeTuple<A extends any[], B extends any[]> = [...A, ...B]; I have tried the following approach: type MergeTuple<A extend ...

Clicking on the child element triggers a blur event

I have a situation where a parent element contains an input: <div @blur="onLeaveSelect($event)"> <div v-if="searchActivated" > <input type="text" placeholder="Search..." @mousedown.stop> ...

The function called v1.isEqual is throwing a TypeError because it is not recognized as

When working on my NextJs/React project, I encountered an issue while using the useCollectionData hook. The problem arises when fetching posts from my firestore database, resulting in the error message TypeError: v1.isEqual is not a function Below is the ...

What causes an error in RSVP Deferred when a promise is invoked multiple times?

What causes an error in RSVP Deferred when the promise is called twice? There appears to be a distinction between deferred.promise.then().finally() and deferred.promise.then(); deferred.promise.finally(). Why is this? RSVP.on('error', functio ...

Spin the div towards the location of the mouse

Is it possible to create a rotating effect on a div element based on the position of the mouse pointer? I envision the div displaying <- when the mouse is on the left side, and -> when the mouse moves to the right, regardless of direction. If anyon ...

"What is the best way to have a data toggle in Vue that waits for the success or failure of

How can I ensure that the modal is triggered only after a successful axios response, without altering any existing styles? The current code triggers the modal before waiting for the axios response, despite adding v-if. Current code: <template> <d ...

Changing a class using JavaScript: Adding and removing class dynamics

Currently, I am attempting to create a function that will toggle the visibility of a visual object on and off whenever the user clicks on it. Additionally, I need to implement a click event listener within the HTML class named btn-sauce. Unfortunately, my ...

Looking to showcase the array list on the user interface

I'm attempting to use the map function in JavaScript to display a list, but I keep encountering an error that says "TypeError: Cannot read property 'map' of undefined". import React, { Component } from 'react' import constants fro ...

Sample code for table_class_list and table_row_class_list is provided below:

I am excited to start using the newest version of the TinyMCE plugin, with its enhanced features. I experimented with the URL to understand how the table plugin functions. In the example provided, I noticed two classes named Dog and Cat, each associated ...

modifying input field with radio button selection in Jquery

Is there a way to set the input field to have a default value and then change it, or disable it with a different value? $("#tax").value(19).prop("disabled",false); $("#tax").value(0).prop("disabled",true); <script src="https://ajax.googleapis.com/aj ...

Transferring data between functional components in ReactJS and dealing with the output of [object Object] or undefined

I'm struggling with passing a prop in functional components that are both located in the same .js file. I previously attempted to seek help for this issue, but unfortunately, it wasn't productive. My goal is to extract the member_id from the GET ...

Is there a way to rearrange the selectpicker selection based on the user's choice?

I'm in the process of setting up a selectpicker that allows users to choose multiple options from a dropdown list. The challenge is that the values extracted by my backend need to be in the order of user selection, rather than the original order of th ...

Problem with Gulp-Watch Functionality on Windows 7 - Node.js, NPM, and Gulp All Up and Running Fine

As someone who is new to the world of Node.js, NPM, and other modern tools designed to improve productivity and workflow, I find myself faced with some challenges. Below are the specifications: Node version - v8.10.0 Gulp CLI version - 2.0.1 Gulp Loca ...