Every time a button is clicked on the interface, a new element or button will appear. This functionality is made possible through

Currently diving into a new React.js project as a beginner. I have a little challenge in the code snippet below - looking to add a button that displays "Hello World" every time it's clicked using setState. Can anyone guide me on enhancing the DisplayMethod() function?

class MessageDisplayed extends React.Component {
  constructor(props) {
    super(props);
    this.state = {message: "Hello World"};
    this.DisplayMessage = this.DisplayMessage.bind(this);
  }
  
  DisplayMessage() {
    this.setState(state => ({
      //Need assistance in adding more "Hello World" buttons each time it's clicked.
    
    }))
  }
  
  render(){
    
    
    return (
      <button onClick={this.DisplayMessage}><h1>{this.state.message}</h1></button>
    )
  }
}



ReactDOM.render(
  <MessageDisplayed />,
  document.getElementById("root")
); 

Answer №1

In the event handler, you have the capability to simply add the text "Hello World" to the existing message in the functional state update.

DisplayMessage() {
  this.setState(state => ({
    message: state.message + "Hello World"
  }))
}

class MessageDisplayed extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: "Hello World" };
    this.DisplayMessage = this.DisplayMessage.bind(this);
  }
  
  DisplayMessage() {
    this.setState(state => ({
      message: state.message + "Hello World"
    }))
  }
  
  render(){
    return (
      <button onClick={this.DisplayMessage}><h1>{this.state.message}</h1></button>
    )
  }
}

ReactDOM.render(
  <MessageDisplayed />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root" />

Utilizing an external message content

const message = "Hello World";

class MessageDisplayed extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message };
    this.DisplayMessage = this.DisplayMessage.bind(this);
  }
  
  DisplayMessage() {
    this.setState(state => ({
      message: state.message + message
    }))
  }
  
  render(){
    return (
      <button onClick={this.DisplayMessage}><h1>{this.state.message}</h1></button>
    )
  }
}

ReactDOM.render(
  <MessageDisplayed />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />

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

Is there a way to send a promise resolve or reject from a function code within router.post() in Express?

Below is my code in express (node.js) router.post('/example.json', function (req, res) { // getFileInfo is a function to return an array return getFileInfo(req.body.fileList).then((array) => { axios({ method: 'post', ...

when the AJAX request has a specific condition

When making an AJAX request, I want to pass data only if a certain condition is met. The "data: testobj" line represents a JSON object that will return {"name":"tom"} $.ajax({ type: "POST", url: 'test.asp', data: testobj, succes ...

Utilize API to import sunrise and sunset times based on specific coordinates directly into a Google Sheet

After countless hours of trying to crack this code, I’m faced with a final hurdle. The challenge lies in parsing the output from the and storing either the sunrise or sunset time into a variable that can be exported as a result in a Google Sheet. The u ...

Managing the Response from Google Geocode API in a Vue JS Component

I am facing an interesting challenge. I have a scenario where users can choose between two options - using their current location or entering a zip code. When a user inputs a zip code, I need to make a call to the Google geocode API to retrieve the central ...

POST request in Ajax with NodeJs/MongoDB/Mongoose causing an Uncaught TypeError: Illegal invocation

Whenever I attempt to make a POST request using Ajax/Jquery, I keep encountering an error in the console. The specific errors are on lines 67 and 31 in the createTeam.js file: $.ajax({ //line 67 sendInvitation(teamID,_companyName,teamName) //lin ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

Choosing the Right Project for Developing HTML/Javascript Applications in Eclipse

Whenever I attempt to build a webpage using eclipse, I am presented with two choices: -- A Javascript project -- A Static web project If I opt for the former, setting up run to open a web browser can be quite challenging. If I decide on the latter ...

Leveraging the power of Ajax in JavaScript

For my assignment, I successfully made two separate paragraphs hide and show using jQuery. Moving forward, the next step involves integrating JavaScript Ajax code to allow the paragraphs to toggle visibility. To achieve this, I created two distinct HTML fi ...

Mat-SideNav in Angular Material is not toggled by default

<mat-toolbar color="primary"> <mat-toolbar-row> <button mat-icon-button> <mat-icon (click)="sidenav.toggle()">menu</mat-icon> </button> <h1>{{applicationN ...

Editing the object retrieved from JSON is not possible once it has been fetched

Project. Input text in the field and it appears on the shirt. When you click "see back," there is an issue where new text overlaps old text. Clicking on "see front" allows you to enter new text, with the previous text saved underneath. Question: How can ...

Issue with Electron and Node.js: Application fails to launch due to inability to locate the app within the modules

I am currently testing out an electron application that is supposed to link to our website. I decided to follow one of the tutorials available. Unfortunately, upon launching the app, I encountered the following error: Error log : akshay@akshay-mint-deskt ...

Developing a unique JavaScript object by extracting information from a jQuery AJAX response

Is there a recommended approach for creating a custom JavaScript object that contains data retrieved from a jQuery AJAX request? I'm considering two methods, but unsure which is the most appropriate. The first method involves including the AJAX reques ...

What is the best way to pass the username and token data from a child component to its parent component

Hey, I'm currently working on a login app in React where the login component is a child of the app. My goal is to send back the username and token to the parent component once a user is logged in, so that I can then pass this information to other chil ...

Setting Default Value for Autocomplete in React

I'm facing an issue with the default value in my autocomplete feature within my React app. Even though I set a default value, when I try to submit the form, it still shows as invalid because it appears to have no value until I manually click on the au ...

The NEXT.js API endpoint is not configured to handle POST requests

I am having an issue with my Next.js API route located at "pages/api/contact". The API appears to be working when I process a GET request or navigate to localhost:3000/api/contact. However, when attempting to process a POST request to this API ro ...

Combining two JSON objects using Angular's ng-repeat

My goal is to extract data from two JSON files and present it in a table: The first file 'names.json' contains: [ { "name": "AAAAAA", "down": "False" }, { "name": "BBBBBB", ...

Error Encountered in Next.js: PDFtron Webviewer - Troubleshooting

I'm currently working on a website that incorporates a dynamically imported PDF viewer within the page. When running the code locally, everything operates smoothly with no errors. However, when executing the "npm run build" command, I encounter the fo ...

Using Vue Js directive to implement a Select2 component

I've been exploring the example of the Vue.js wrapper component and trying to customize it to use a v-select2 directive on a standard select box, rather than creating templates or components for each one. You can view my implementation in this JS Bin ...

Transmit a document to the server using axios within a react application

I'm having trouble using axios with React to send a file to the server. I can't seem to figure out what's wrong as there are no error messages. The form variable appears to be empty and I'm stuck on how to proceed. Location: React subm ...

What is the proper method for running a script using the Selenium JavascriptExecutor?

On my test.html page, I've included the following code snippet: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> </head> <body> ...