A React component that dynamically increases the padding CSS value to render its children components

Greetings! I am working on a scenario where a React component needs to pass a padding value to styled components while incrementing it based on the nested rendering level. For example, imagine a List component that must display a parent and child component with additional padding. I have implemented it as shown below, but I am unsure if the useEffect and useState usage is appropriate in this case. I am concerned about potential side effects. Here is the list component:

const Parent = ({ title, children }) => {
  const [padding, setPadding] = useState(0);
  useEffect(() => {
    setPadding(padding + 20);
  }, []);
  
  return (
    <ListStyle padding={padding}>
      <div className="listItemCategory">{title}</div>
      <div className="wrap">
        <div className="listItem">{children}</div>
      </div>
    </ListStyle>
  );
};

Feel free to check out the codesandbox link for more details HERE

Answer №1

If you're looking for a solution, consider using useRef and useLayout. useRef alone might be able to address your issue effectively.

import React, { useLayoutEffect, useRef } from 'react';

const Parent = ({ title, children, padding }) => {
  const nestedPadding = padding.current + 20;

  return (
    <ListStyle padding={nestedPadding}>
      <div className="listItemCategory">{title}</div>
      <div className="wrap">
        <div className="listItem">{children}</div>
      </div>
    </ListStyle>
  );
};

const List = () => {
  const padding = useRef(0);

  useLayoutEffect(() => {
    padding.current += 20;
  }, []);

  return (
    <div>
      <Parent title="Parent" padding={padding} />
    </div>
  );
};

On the other hand, I suggest considering useState as it offers a more direct approach. useRef is commonly used for manipulating DOM elements or maintaining values across renders, rather than managing component state.

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

Using jQuery Mobile to manipulate the window location in Chrome can cause unexpected jumping behavior

After clicking on a link, I am creating a URL for a clickonce application using an ajax call. Once the ajax request successfully receives the generated link, I use window.location = my_generated_link; This process functions correctly in IE9 – the clicko ...

Unable to load CSS background image and update code

After writing the code in my CSS file, /*The code I initially wrote*/ .wrapper::before { content: ""; position: absolute; bottom: -30%; left: 0; height: 100%; width: 100%; background: url(../img/homeTrans2.svg) no-repe ...

methods for verifying changing row array data in javascript

Can someone please provide guidance on how to validate the array values in JavaScript? Below is the code I am currently using. The issue I am facing is that even after filling up all the values, I still receive a validation error message. Please advise me ...

Error: Unable to run 'play' on 'HTMLMediaElement': Invocation not allowed

Just a simple inquiry. I am trying to store an HTMLMediaElement method in a variable. // html segment <video id="player" ... /> // javascript segment const video = document.querySelector('#player') const play = video.play video.play() / ...

Is it possible to apply a tailwind class that fades or transitions into something else after a specific duration?

How can I achieve a transition effect from the bg-red-300 class to bg-transparent, or a different background class, over a 2-second duration? Do I need to use javascript for this effect? I would like an element to be highlighted and then return to its no ...

Press the onClick button to return to the previous page or component in a React application

I currently have a div that switches from one component to another by toggling the state when a button is clicked. { !showForm ? ( <div className={styles.showTicketContainer}> <div className={styles.showTicketBox}> ...

Encountering a glitch in Jest unit testing post updating to npm version 3.3.12

After updating my project to node 5.1.0, npm 3.3.12, and updating all dependencies, I am now facing a plethora of errors! Originally, I encountered the same error as discussed in this GitHub issue: https://github.com/facebook/jest/issues/554, which was re ...

Extracting the value of an HTML element from a string variable in AngularJS

I am facing an issue with my application where the content of an HTML element is received as a template from the server. I am attempting to assign this template, which is essentially a string, and have the variables within the template linked to the contro ...

Block of white colors located on the right side beyond the confines of an HTML structure

I am encountering an issue where a white block is appearing outside the HTML on my page. Despite having no content, Firebug indicates that it is located outside the html tag. I suspect the problem may be related to an image that is too wide or padding exc ...

The context environment is failing to update the current state

Working with context in React can be tricky for some, including myself. I was hoping the new Context API would make things easier, but I'm still facing some issues. While I can get the initial value to display, the updates based on my Effect are not r ...

What steps can I take to stop text from disappearing when the screen size decreases and the span is used?

I'm currently using Bootstrap 5 to create a form. On a computer screen, my file input element looks like this: https://i.sstatic.net/fX6Kx.png However, on mobile devices, it appears like this: https://i.sstatic.net/ilUZ9.png Below is the code sni ...

What is the best way to implement a delay for ajax requests triggered by onkeyup events, and then restart the delay countdown each

Is there a way to add a delay for ajax requests triggered by onkeyup and reset the delay if onkeyup is triggered again? For instance, consider this code: When a user enters data into id="fname" triggering an onkeyup event, a loading span id="loading" wil ...

What is the process for assigning a value to the body in a div element?

Within a div, there is a body element structured like this: <div id = "TextBox1"> <iframe id = "TextBox1_1"> #document <html> <head></head> <body></body> </html> </iframe> </div> I have attempte ...

A guide to customizing the label color in Material-UI's <TextField/> component

How do I change the text color of the "email" label to match the border color? Below is the provided code: import React, { Component } from "react"; import { Icon } from "semantic-ui-react"; import { Divider } from "semantic-ui-react"; import { TextField ...

Click to refresh React list

Why is the display of the map function only updating on input change? Can someone provide an explanation? Even though I am using useEffect to refresh the page on stack change, it is not working. Only input field change is updating the display. import Reac ...

What is the best way to invoke a function within a component class from my App.tsx file?

I am a beginner in the world of React Native, currently working on creating a mobile app using Expo. My challenge lies in calling a function from a component class within my App.tsx file. I specifically do not want this function to be static because I nee ...

React JS alterations in circular word cloud

I have a unique project with a dynamic word cloud feature displaying random words. My goal is to customize the code so that the word cloud can showcase specific words from a list of my selection, like: let WordList = ['Apple', 'Banana' ...

In Protractor, mastering the technique to extract multiple values simultaneously is crucial for efficiently handling applications that receive a large amount of push notifications

I am currently developing an automation test using Protractor for an application that receives a large volume of push notifications. The issue I am facing is testing a simple logic. expect(A + B).toEqual(C); The problem arises because A, B, and C are sou ...

Tips for successfully passing props with getAsyncComponent on React Route

I need to utilize props with APIs import {getAsyncComponent} from 'async-react-component'; const Apis = () => import(/* webpackChunkName: "apis" */ './app/components/Apis/Apis'); Within the render() method: return ( <BaseL ...

Is the space-between property not delivering the desired spacing?

I am trying to achieve equal spacing between list items, and I attempted the following code. ul { list-style-type: none; display: flex; justify-content: space-between; } However, it seems that this approach is not working as expected. I am confused ...