What is the best way to allow a number to be editable when clicked on in a React application

Currently, I am trying to find a solution for making a number editable when clicked without having to use form inputs or other React libraries that don't fit my requirements. The provided screenshots showcase the desired interface.

https://i.stack.imgur.com/Dewzx.pnghttps://i.stack.imgur.com/6GzSc.png

In order to maintain consistency in the user interface, my approach involves adding a border around the number upon clicking the edit button. Below is a simplified version of the code to illustrate the functionality:

constructor() {
    this.state = {
        editModeEnabled: false
    }
}

handleEditClick() {
    this.setState({
        editModeEnabled: !this.state.editModeEnabled
    })
}

render() {
    let numberBox = null
    if (this.state.editModeEnabled) {
        numberBox = {
            border: '1px solid blue',
        }
    }

    <span style={dollarStyle}>$</span>
    <div style={numberBox}>
        {this.props.number}
    </div>

    <button onClick={this.handleEditClick.bind(this)}></button>
}

I am exploring options on how to make the number editable within an input field while maintaining its original appearance. While attempting to enclose the number with an <input> tag, I encountered challenges in styling it effectively.

Answer №1

Customize the appearance of the <input> element using CSS. While there are alternative methods to achieve this, utilizing CSS for its intended purpose is the most straightforward approach. The example below serves as a starting point, and adjustments may be necessary based on your specific platform(s) and design requirements. By sticking to CSS, you can avoid the complications that come with non-CSS workarounds.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editModeEnabled: false,
    }
  }
  
  handleEditClick() {
    this.setState({ editModeEnabled: !this.state.editModeEnabled });
  }

  render() {
    return (
      <form>
        $<input type="number" value={this.props.number} disabled={!this.state.editModeEnabled}/>
        <a role="button" title="Edit" onClick={this.handleEditClick.bind(this)}>✏️</a>
      </form>
    );
  }
}

ReactDOM.render(<App number={5}/>, document.getElementById('container'));
input {
  border: 1px solid blue;
  display: inline-block;
  box-sizing: inherit;
  margin: 0;
  padding: 0;
  width: 2em;
  line-height: inherit;
  vertical-align: inherit;
  text-align: right;
  color: inherit;
  font: inherit;
  background: none;
}

input[disabled] {
  border: 0;
}

a { cursor: pointer; text-decoration: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

Answer №2

If you want to make your content editable, one option is to utilize the

<div contenteditable="true">
tag.

However, it may be more appropriate to customize the style properties of your input, as using contenteditable comes with HTML properties that may not be necessary for your purposes.

Answer №3

If you're looking to enhance your website, consider using Bootstrap 3, Jquery, or JQuery UI. Bootstrap stands out as the top choice here due to its abundance of resources available online. Another option to explore is "X-Editable", which allows you to easily make specific fields editable or display a pop-over on input fields. Check it out:

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 Stepper StepIconComponent prop in MUI is experiencing issues when trying to render styles from the styles object, leading to crashes in the app

Struggling to find a way to apply the styles for the stepper component without using inline styles. I attempted to replicate Material UI's demo, but encountered an error. The code from Material UI's demo that I want to mimic is shown below: Here ...

Encountering an error while attempting to add class-constructed objects to an array list in React/NextJs: "Unable to add property 0, as the object is

This function contains the code required to generate rows for display in a Material Ui table. class User { constructor(id, name, email, measured, offset, paidAmount, status, home, misc, plane, transport, partner, isCoupon) { thi ...

A numerical input field that removes non-numeric characters without removing existing numbers?

Currently, I have implemented the following code: <input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')"> This code restricts users from entering anything other than numbers into a field on my webpage. However, I hav ...

What is the method for accessing an image in JavaScript?

Currently, I am developing a currency converter for a gaming marketplace and I would like the users to be able to generate images using JavaScript. While most of the work is completed, I am facing an issue where the images are not displaying properly and i ...

Struggling to place the sans-serif font right at the edge of the H1 tag

Encountering a strange issue that suggests I might be overlooking something simple. Any thoughts on the following: I have a heading tag styled with a sans-serif font (loaded from Google fonts) and when I apply a background-color, the text does not align t ...

retrieving the webpage's HTML content from the specified URL using AngularJS

Utilizing the $http.get('url') method to fetch the content located at the specified 'url'. Below is the HTML code present in the 'url': <html> <head></head> <body> <pre style = "word-wrap: break ...

Nodejs - Utilizing Express and Mongoose to Implement URL Routing by Name

My Express 4 server has CRUD routes specifically for authors: router.get('/authors', AuthorsController.index); router.post('/authors', AuthorsController.store); router.get('/authors/:name', AuthorsController.show) ...

Calculating the dot product of two arrays using JavaScript

let array1 = [2,4,6] let array2 = [3,3,3] let result = dotProduct(array1,array2) // should return 36 Can you suggest a streamlined approach to creating the dotProduct function without relying on external libraries? ...

Is FIREFOX better with plugins or extensions?

I have created a JavaScript function that changes the colors of images on web pages, specifically to assist colorblind individuals in identifying content. The entire development process was done using JavaScript within the Dreamweaver environment, along w ...

Twitter Bootstrap 3.3.5 navigation menu with a drop-down feature aligned to the right

I've been attempting to position the drop-down menu all the way to the right, following the search input field and submit button. I've tried using pull-right and navbar-right classes without success. Is there a method to accomplish this? <na ...

What is the process for spinning an image?

Is there a way to rotate an image around its center? I am looking for a solution where the image rotates continuously when clicked, but stops if an ajax call is unsuccessful. Please assist me in finding a resolution. ...

What is the method for changing the Uint8Array object into a string?

I am encountering a similar issue as the one discussed in this post. I have read the solution provided, but I am having trouble grasping how to implement it. Are there any alternative suggestions? Here is my code snippet: var eccrypto = require("eccrypto ...

Conceal a designated column within a material angular data table based on the condition of a variable

In the morning, I have a question about working with data tables and API consumption. I need to hide a specific column in the table based on a variable value obtained during authentication. Can you suggest a method to achieve this? Here is a snippet of my ...

Next.js fails to update the user interface (UI) when there is a change in

In my latest Next.js project, I am working on a feature that involves looping through an array of amenities. Each amenity is displayed in a div element that, when clicked, toggles the active property. The logic behind this functionality is handled by the ...

What are some ways to personalize a field while inserting a new row using the library material-table?

Is it possible to customize a field in an editable table when adding a row using the material-table library? I want to make a certain field read-only or prevent the user from changing it. I have tried setting the column as read-only, but that only applie ...

I need to use JavaScript to create HTML to PDF and then upload the PDF file to a SharePoint Document Library

Our current project requires us to convert HTML to PDF and save it in a SharePoint Document Library. While we have successfully converted the HTML to PDF using Kendo plugin, we are facing challenges with storing it in SharePoint. It's worth noting th ...

Nativescript encountered an issue while attempting to generate the application. The module failed to load: app/main.js

I'm currently experimenting with the sample-Groceries application, and after installing NativeScript and angular 2 on two different machines, I encountered the same error message when trying to execute: tns run android --emulator While IOS operations ...

Activation of states in response to item clicks

Recently, I started using the US-Map plugin created by newsignature (). I have put together a chart that highlights various state laws for comparison on a per-state basis. Currently, the setup allows me to compare 3 states at a time. Users can easily clos ...

What causes the variation in results when I input CSS directly into the head section versus linking it from a separate .css file?

As a beginner, I am facing an issue with my CSS. When I directly insert the CSS into the head of my .html file, everything looks perfect. However, when I link my .css file into the head, the very first word ("Holy") does not display properly. I have double ...

Issue with React ChartJS rendering – Title not visibleWhen using React Chart

I'm currently using react chart js for displaying a doughnut in my component. "chart.js": "^3.7.1", "react-chartjs-2": "^4.1.0", However, I'm facing an issue where the title is not being displayed: const d ...