By simply clicking a button in a React component, I aim to alter the font style of the text

function makeTextBold() {
  const boldText = document.querySelector('.form-control');
  boldText.style.fontWeight = 'bold';
  setText(boldText);
}

When I click the button, it redirects me to a blank page in the browser.

Answer №1

When utilizing the getElementsByClassName method, it will retrieve a collection of elements with the specified classes.

If dealing with a single element, consider using .querySelector instead.

Alternatively, if you are set on using the getElementsByClassName method, iterate through the collection using a for loop or utilize the .find() method to target the specific element and apply desired styles.

In React, it is recommended to use refs rather than directly manipulating elements with DOM APIs.

Answer №2

It seems you are on the right track with utilizing state, but it is best to avoid mixing native DOM operations with React. React has its own way of updating the DOM which can cause conflicts with traditional methods like using getElementsByClassName to update styles.

In this example, there is a function triggered by a button click that updates the state, changing a concatenated array of class names based on the state. If the state is true, the "italic" class is added and this class string can then be applied to elements in your code.

Note that the style modifications only affect inputs 1 & 3 in this scenario.

const { useState } = React;

function Example() {

  const [ italic, setItalic ] = useState(false);

  function handleClick() {
    setItalic(true);
  }

  const controlStyle = [
    'form-control',
    italic && 'italic'
  ].join(' ');

  return (
    <div>
      <input
        type="text"
        className={controlStyle}
      />
      <input
        type="text"
        className="form-control"
      />
      <input
        type="text"
        className={controlStyle}
      />
      <button onClick={handleClick}>Click me</button>
    </div>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
.form-control { color: red; }
.italic { font-style: italic; color: blue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></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

Unexpectedly, the API is displaying an empty array despite the fact that there is data

Hi all, as a beginner I am currently working on building a React app with an Express backend. I have successfully created an API that retrieves data from MongoDB. When examining the data in MongoDB using Robo3T, I noticed that the options array appears to ...

Tips for effectively creating and appending elements using JavaScript

Code Sample var result=$.getJSON("http://search.twitter.com/search.json?callback=?",{q:query}, function(data) { ... question. }); Query: In order to display each tweet result, I want to ...

Eliminate perfect-scrollbar functionality on mobile devices

I have applied the perfect-scrollbar class with 'height: auto' on mobile screens, expecting it to work properly. It's functioning well in responsive mode on the web. However, it does not scroll on mobile devices. @media (max-width: 992px) { ...

The Alert Component fails to display when the same Error is triggered for the second time

In the midst of developing a Website using Nuxt.js (Vue.js), I've encountered an issue with my custom Alert Component. I designed a contact form on the site to trigger a specialized notification when users input incorrect data or omit required fields ...

Updating the $location variable from the $rootScope perspective

I am facing an issue with my web app which is built using AngularJS. I have two functions in my code - one declared on the $rootScope and the other on the $scope. The code snippets are shown below: app.js app.run(function ($rootScope, $location) { $roo ...

Button within ng-switch statement

Issue with switch button inside switch statement, only functioning correctly outside of the switch statement. See below for my code: <div ng-controller="LoginController as LC"> <div ng-switch on="view.name"> <div ng-switch-de ...

Designing unique page transitions with Next.js

Currently, I am attempting to achieve callback-based route transitions utilizing the Next.js framework and Greensock animation library. For instance, when moving from the homepage to /about, my goal is to have something like: HomepageComponent.transitionO ...

Displaying search results in various Angular components

On my home page (homePageComponent), I have a search feature. When the user clicks on the search button, they are redirected to a different page called the search list page (searchListComponent). Within the searchListComponent, there is another component c ...

Exploring the integration of Jest/Enzyme for testing React components while maintaining JSS style encapsulation

I've been facing some challenges while testing my React components with Jest due to the encapsulation of JSS components. Here's a pseudo code example: JSS(style.js): export default { pinkOnYellow: { color: 'pink', b ...

Utilizing Express.js: A Guide to Fetching File Downloads with a POST Method

Although GET requests are successful, I am facing challenges when using POST to achieve the same results. Below are the different code snippets I have attempted: 1. app.post("/download", function (req, res) { res.download("./path"); }); 2. app.post ...

Having Trouble Showing Loading Component on Next.js v13

Having some issues with setting up a loading component in my Next.js v13 project. I followed the documentation by creating a file called loading.tsx in the src directory, but it's not appearing on the page as expected. I've also included a functi ...

Unable to resize images in Firefox

Why is it that resizing doesn't seem to work in Firefox but functions fine in Internet Explorer? I'm struggling to find a way to make it consistent across all browsers. My goal is to resize the width to 800 and height to 475, disable maximizing t ...

The Crimson Thread when incorporating tsx into Next.js

While working with TSX in React and TypeScript, I encountered an issue. A red line appeared on the screen even though the project runs successfully. Can anyone explain why this red line is appearing and why the classes in TSX are not functioning properly ...

Sending values from multiple radio groups in JavaScript can be done by accessing each group individually and extracting

This is an add to cart system. Currently, I am able to send quantity with an ID. However, I also want to send radio group values. How can I achieve this? Here are my codes: product.php <script> jQuery(function ($) { $('.popbutton').on(&a ...

Troubleshooting an issue with a Typescript React component that is generating an error when using

I am in the process of implementing unit testing in a Typescript and React application. To start off, I have created a very basic component for simplicity's sake. import React from "react"; import ReactDOM from "react-dom"; type T ...

Attempting to verify JavaScript input by utilizing OnClick and a custom function. Regardless of the content inputted, the system consistently confirms that the format is accurate

I am currently working on a project that involves an HTML file and an external JavaScript file. In the HTML file, there is user input and a validation button that triggers the courseValidation() function when clicked. However, I am facing an issue with the ...

Adjust the size of an HTML image for printing using a JavaScript window.print() function

On my website, I have a print option set up where specific elements are hidden using @media. How can I adjust the size of an image within the @media query when my JavaScript print function is triggered? I am able to modify a regular div element easily, but ...

Converting Blob to Base64 using javascript

I've managed to successfully convert my base64 (DATA_URI) image into a blob, but I'm facing issues with reverting it back. Here's what my base64 to blob code looks like for better understanding. Check out this link. b64toBlob(b64Data, cont ...

Can anyone tell me the best way to access the name attribute of an HTML element in TypeScript?

Currently, my code is utilizing the name attribute to verify whether the user has entered information in a specific field and validating the input. However, I am facing an issue where the submit button remains active even if there are empty fields presen ...

The useNavigate() hook from react-router-dom is not properly setting the id in the URL path

I am currently using react-router-dom v6 for my routing needs. My goal is to pass an ID in the navigate URL path. Here is the onClick method and button code that I am working with: let navigate = useNavigate(); const routeChange = (id) => { let ...