Creating a list element after clicking in ReactJS is achieved by using event handlers in

I have buttons and inputs that I want to use to generate a list item in the ul section at the end of my code. However, despite adding functions to handle this feature, it still doesn't work as intended.

import { useState } from 'react';
import './App.css';

function App() {

  const [income , setIncome] = useState(0) 
  const expense = 10 
  const balance = income - expense
  const [firstValue , setFirstValue] = useState("")
  const [secondValue , setSecondValue] = useState("")

  const handleChange = event => {
    setSecondValue(event.target.value)
  }

  const handleInputChange = event => {
    setFirstValue(event.target.value)
  }

  function updateIncome(event) {
    setIncome(event.target.value)
  }

  const createListItem = () => {
    return(
      <li>{firstValue}</li>
    )
  }

  function checkMaxLength (object){
    if (object.target.value.length > object.target.maxLength) {
     object.target.value = object.target.value.slice(0, object.target.maxLength)
      }
    }

  function buttonOnClick() {
    createListItem()
  }

  return (
    <div >

      <header>
        <div className='App'>
        Expense Tracker
        </div>
      </header>

      <main className='main'>

        <div className='income-box'>

          <div className='income'>Income

            <div className='numbers'>
              {income + "$"}
            </div>

          </div>

          <div className='expense'>Expense

            <div className='numbers'>
              {expense + "$"}
            </div>

          </div>

        </div>

        <div className='income-input'>
          <input type="number" min="0" maxLength = "8" onInput={checkMaxLength} className='input' placeholder='Enter your Income' onChange={updateIncome}/>
        </div>

        <div className='total-balance'>
          Total Balance : {balance}$
        </div>

        **<div className='add-item'>Item
          <input type="text" className='adding-input' placeholder='Add Item' onChange={handleInputChange}/>
        </div>

        <div className='add-item'>Amount
          <input type="number" className='adding-input' placeholder='Add Amount' onChange={handleChange}/>
        </div>

        <div className='add-button'>
          <button type="button" className='expense-button' onClick={buttonOnClick}>Add Expense</button>
        </div>**

        <div>
          <ul>
            {createListItem}
          </ul>
        </div>

      </main>
      
    </div>
  );
}

export default App;

Answer №1

Implement a state to store the values for the <li>s:

const [values, setValues] = useState([]);

In the <button> onClick event handler, add the firtValue and secValue to the state:

function handleClick() {
  setValues(values.concat(`${firtValue} ${secValue}`));
}

Create the listOfLi by mapping over the values:

const listOfLi = values.map((value, i) => <li key={i}>{value}</li>);

Here is the complete code snippet:

import { useState } from 'react';

... // Other component logic remains unchanged

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

The necessity for unique "key" props for every child in a list is generating an error within the custom component

When mapping over an array to render a custom card component for each index, I encountered an error stating "Each child in a list should have a unique key prop." Despite passing the index as the key and trying various methods like using React.Fragment or ...

Error: Element not found. Element with the specified XPath query '//button[normalize-space()='LOAD MORE']' could not be located

My current project involves creating a web scraper that is designed to continuously scroll down a page until it locates the "Load More" button and then clicks on it. However, I am encountering an issue where the program is unable to find the specified butt ...

The current version of HTML5 Context Menus is now available

I'm in need of implementing the HTML5 Context Menu feature. Currently, only Firefox supports it. My main objective is to add some menu options without replacing the existing context menu. How can I achieve the same functionality now? I am aware of va ...

Instructions for setting the login component as the default route instead of the home component

//layout.js: "use client"; import { Inter } from "next/font/google"; import "./globals.css"; import Header from "./layouts/Header/Index"; import Sidebar from "./layouts/Sidebar/Index"; import Footer from & ...

Can you explain the difference between the <li> and <div> elements in HTML? How are they used differently

I'm currently exploring the elements for Selenium usage. I have a question about the <li> tag in HTML - could you explain its significance to me? Also, how does it differ from the <div> tag? ...

Tips for dynamically resizing an image to suit any screen size, such as with Bootstrap 4

I am having trouble centering an image on the screen and making sure it fits properly without requiring the user to scroll (on screens larger than a tablet). Here is my desired outcome: https://i.sstatic.net/LbfV8.png The top row shows the expected resu ...

Creating a fieldset and form in HTML code involves using

I encountered a strange issue recently. I had set up a form in HTML to send data to my PHP script, and everything was functioning correctly. However, the design looked a bit messy without margins, so I decided to make some CSS adjustments. After applying s ...

Verifying the visibility status of a div and toggling a class based on it

I'm facing a challenge with multiple checkboxes in a row. When a button is clicked, it displays a div (#locale_container), and flips a small arrow by adding a rotated class. However, I only want the arrow to flip when the div is being shown or hidden ...

Create JavaScript variable from either HTML or database sources

Hello, I am trying to implement a counter that retrieves its value from a JavaScript file, but I would like to customize it. Below is the JavaScript code: function updateCounter(count) { var divisor = 100; var speed = Math.ceil(count / divisor); ...

Contact form script malfunctioning, showing a blank white page

Encountering a white screen when trying to submit my contact form with fields for Name, Email, Subject, and Message. I am looking to receive emails through my website. I have double-checked all variable names and everything seems to be correct. Since I am ...

Tips for enabling selection of list items in an input tag

Below is the code I have written to create an InputFilter. MyFilter = function(args) { var dataUrl = args.url; var divID = args.divID; var div = document.getElementById(divID); var myTable = '<input type="text" id="myInput" on ...

Transforming HTML into PDF files with PHP, not the other way around

As a PHP developer, I have a project that requires converting a set of HTML documents (approximately 30 to 50 pages) into PDF files. After conducting some research, I have found several potential solutions. These include various PHP libraries and command ...

Nextjs unexpectedly displays blank page upon fetching data from Firebase Firestore without any error messages

I am currently facing an issue when trying to retrieve page details from Firebase Firestore using getStaticPaths and getStaticProps in my Next.js project. Despite following the code structure correctly, I am encountering a scenario where the page appears e ...

Tips for choosing the most current or upcoming item from a list using buttons

I am currently working on a small website project for one of my lessons. The task involves selecting items from a list and using two arrows to navigate to the item above or below the current selection. Here is an example: https://i.stack.imgur.com/FxZCN. ...

What is the process for linking functionality to buttons in Embedded Elixir?

When it comes to rendering templates, I follow this method: <%= for country <- @countries do %> <div> <div>A compilation of countries you have visited</div> <a href="/countries/<%= String.downcase(country) %& ...

Guide on efficiently injecting data into a database using JavaScript and SQL from an array of objects

Let's simplify this process. I am creating a dynamic form for clients to submit data to a PostgreSQL database using React on the front end and NodeJs on the back end. Once the form is filled out, the inputs are stored in an array of objects like this ...

Error: JavaScript alert box malfunctioning

I am facing an issue with my JavaScript code. I have successfully implemented all the functionalities and can change the color of an image background. However, I am struggling to prompt a pop-up message when clicking on an image using "onclick". I have tri ...

Tips for refreshing a React component following an update with Redux and hooks

Currently, I am working on a next.js page that includes the following code: const Index: NextPage = () => { const state = useSelector((state) => state); useEffect(() => { // API call to fetch comments list and store data using use ...

Steps for Deactivating Past Dates on JQuery Datepicker1. Open your

I've been working on a custom JQuery Calendar for selecting appointments, with the requirement to disable dates prior to the current date and highlight available dates in an orange color (#f48024). Unfortunately, my attempt using minDate hasn't b ...

Displaying divs in a reverse order can bring a unique perspective

I have multiple sibling divs that are styled with position: fixed; display: table; top: 0; left: 0; width: 100%; height: 100%;. These divs act as message boxes and are created by a third-party ASP.NET control, preventing me from altering their order in t ...