"Utilizing React.js to implement white-space styling on numeric values for

I am a beginner in Reactjs and eager to learn and improve. Here is some code I have been working on: there's an <h1> element with the text "test", and beneath it, I want to display numbers vertically like this: 1:1, 1:2, 1:3. However, the CSS doesn't seem to apply to the numbers. I can see the numbers but they lack styling, and there are no error messages either. Is there something wrong with my code?

import React, { Component } from 'react'

class Button extends Component {

    state = {}

    button = () => {

        const proxyurl = "https://cors-anywhere.herokuapp.com/";
        const url = "http://*****.*****.com/numbers.txt"; 
        fetch(proxyurl + url) 
            .then(response => response.text())
            .then(contents => document.write(contents))

    }


    render() {
        return (
            <div>
                <h1>test</h1>
                <div style={{ color: 'red' }}>{this.button()}
                </div>
            </div>
        );
    }
}

export default Button;

CSS:

body {
  background: url('***.png');
  color:red;
  margin:50px 0; 
   padding:0px;
   text-align:center;

  
}

  #root {
    white-space: pre;
  }
  

Answer №1

It is important for your render function to be pure, as outlined in the documentation here: https://reactjs.org/docs/react-component.html#render:

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.

In your current render function, there is a call to this.button. This means that every time your component re-renders, a new fetch request is made when it should ideally only be called once. As advised in the documentation, consider moving this logic into the componentDidMount method.


Now, let's address the issue at hand. You are utilizing document.write, but it seems there may be some confusion on how this function operates. Keep in mind that Document.write will essentially wipe out all existing event listeners on the page and replace all content within the body with the supplied argument. Therefore, if you had a root element with an ID of root (

<div id="root">...</div>
), it would have been removed after executing document.write, causing the CSS selector #root to lose its target element.

Instead of relying on document.write, try storing the content in your component's state and rendering it from there:

import React, { Component } from "react";

export default class Button extends Component {
  state = {
    contents: null
  };

  componentDidMount() {
    const proxyurl = "https://cors-anywhere.herokuapp.com/";
    const url = "http://*****.*****.com/numbers.txt";
    fetch(proxyurl + url)
      .then(response => response.text())
      .then(contents => this.setState({ contents }));
  }

  render() {
    return (
      <div>
        <h1>test</h1>
        <div style={{ whiteSpace: "pre" }}>{this.state.contents}</div>
      </div>
    );
  }
}

If you are working with React, remember that there should typically be no need to resort to using document.write. Even for testing purposes or implementing features like page reloads or turbolinks, there are usually better alternatives available.

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

Building a web application using Django REST framework and React JS, and utilizing Axios to post JSON data with an image file included

Is there a way to upload image files to the Django_Rest framework using axios? I have a basic model: class Article(models.Model): title = models.CharField(max_length=120) text = models.TextField() img = models.ImageField(upload_to='articl ...

Enhance the aesthetic appeal of the Search and Filters component in ASP.NET Core using Bootstrap styling

I am struggling to enhance the style and layout of multiple search filters on the page so that the User Experience is improved. I'm unsure how to effectively design this search component. <section class="search-sec"> <div class=&qu ...

The rendering of graphs in FusionCharts is experiencing delays particularly in Internet Explorer, with Chrome performing more efficiently in comparison

I am currently utilizing FusionCharts to generate and display graphs. My requirement is to load over 60 graphs on a single page. Upon testing the page loading in Internet Explorer 11, it is taking approximately 5 minutes. However, when using Google Chrom ...

Convert a JavaScript object into a serialized form

Alright, so here's the thing that's been bugging me. I have this JavaScript object that I need to pass to a PHP script using jQuery AJAX. But every time I try to pass it as is, I get an error. It seems like the object needs to be serialized befor ...

Icons positioned centrally while floating to the left

There seems to be an issue with centering the icon CSS: .icons .overview { position: relative; float: left; width: 16.6666666667%; text-align: center; overflow: visible; } .icon { display: inline-block; width: 64px; heigh ...

Exploring the Issue of Flickering in 3D Models with Three.js and Potree

Currently, I am working with a gltf model from this link: using Three.js and Potree. However, I am facing an issue with the model flickering. I have gone through similar posts on this topic like Flickering planes and Texture/model flickering in distance ( ...

React Native App Command Cannot Be Created

I am attempting to develop a react native application using the create-react-native-app command. I have successfully installed npm. To install create-react-native, I ran the following command in my terminal (on a mac). sudo npm install -g create-react-nat ...

Assessing efficiency through the lens of SeleniumWebDriver versus native JavaScript

Imagine a scenario where an action is triggered by clicking a button on a webpage. Let's say this action takes X seconds to complete, and during this time a div appears in the center of the page. Once the action is done, the div disappears, and focus ...

What could be the reason for this JavaScript malfunctioning in both Chrome and Safari browsers?

Why is it that the javascript works fine in Firefox for the gallery on the page below, but doesn't seem to be functioning properly in Chrome and Safari? In Chrome, the big image isn't displaying but the thumbnails are, and in Safari nothing show ...

Why am I receiving varied results when trying to filter for distinct date values?

While attempting to filter unique dates, I've noticed that the output varies. In some cases, it works correctly, while in others, it does not. I'm having trouble figuring out what's causing this inconsistency. The filtering method below gene ...

Convert form data into a JSON object utilizing JQuery and taking into account nested JSON objects

Currently, I am facing an issue while extracting data for submission using the jQuery `serializeArray()` function. This function works efficiently by providing an array of { name: value } objects, where the name corresponds to the elements in the form. How ...

Utilizing Conditional Statements Within a Map Function

A DataGrid on my frontend application displays data fetched from a MongoDB backend. The data corresponds to keys defined in the MongoDB documents, each containing a set of boolean values. My goal is to check if any of these boolean values are true and disp ...

Issue with font selection in Fabric.js

I am currently working with fabric js version 1.7.22 alongside angular 7 to create a text editor. I have encountered an issue when trying to add text to the canvas using a custom font as shown in the code snippet below. var canvas= new fabric.Canvas(&apos ...

React Native - Listview triggering multiple refreshes when pulled down

As I attempt to implement the onScroll function for ListView to detect when a user has pulled the list down beyond a certain pixel value in order to trigger an AJAX call and refresh the list, I am facing an issue where it fires multiple times leading to a ...

Display the icon beneath the list item label

How can I display the ion-edit icon below the list names? The icons are currently appearing on the right side of each list name, but I want them to be aligned below with some spacing. When clicking on "Data Source Connections," a sublist will be shown whe ...

Determine the Button's State by Monitoring Changes in the TextBox Text

I have been tasked with developing a web application for my company. The main components of the application are a button and a textbox. My goal is to allow users to input a value into the textbox, which will then be processed when they click on the button ...

MUI Version 5: Is it necessary to have @emotion/react or @emotion/styled installed in order to utilize the sx prop?

I recently upgraded my project from version 4 to version 5, and I am exclusively using the sx prop. Despite not having installed @emotion/react, everything appears to be functioning correctly. Is there a compelling reason for me to install @emotion/react ...

ShadowBox replacement for IE8

After much experimentation, I am on the verge of achieving an inset box shadow for IE8 without relying on JavaScript. Take a look at the screenshot below: https://i.sstatic.net/2kM3R.png Since Internet Explorer versions 5.5 through 8 only support Micros ...

What steps can you take to resolve the "TypeError: Cannot read property 'id' of undefined" issue?

I have been developing an app that involves using databases to add items for users based on their user ID, which is their username. However, whenever I attempt to add an item, I encounter an error that I can't seem to troubleshoot. The error message r ...

Error: The URI you are trying to access is restricted and access has been denied

I'm facing an issue with my HTML file that contains multiple d3-graphs embedded directly within script tags. When I try to move one of the graphs to an external JavaScript file, I receive the following error message: "NS_ERROR_DOM_BAD_URI: Access to r ...