0

I would like to know how to apply CSS dynamically to all the elements in a page that belong to a CSS class in React JS? Currently I am using the following:

document.querySelectorAll('.my-paragraph-class').forEach(function (x: any) {
  x.style.fontSize = `${data.value}%`;
});

It works but I would like to know if there is a more efficient way instead of using document.querySelectorAll?

Also when the page loads new text, document.querySelectorAll has to be called again after the text loads, which is not ideal. I would like to know how to persist the modified CSS changes when new text is loaded dynamically?

Thank you in advance

1 Answer 1

1

For applying a static font size to a class you shouldn’t have to use JavaScript at all.

In your css file just do:

.my-paragraph-class: {
 font-size: 10rem || whatever;
}

To dynamically add styling you could use a CSS in JS tool like styled components. For styled components you would import styled components and then write a code outside of your react function like this:

const StyledParagraph = styled.p`
 font-size: 10rem || ${props => props.fontSize}
`

In your JSX you would do something like:

 <StyledParagraph fontSize=“10rem”> Filler Text </StyledParagraph>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! @Kyle currently my component has a font size selector that increases or decreases the font size according to user selection. I will give it a try passing the font size as a parameter on the component that contains the paragraphs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.