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

Updating Mysql through REST API/JWT using PUT method is not possible

I have been attempting to send an update request using Jwt (Tokens) and Node.Js with a backend in mysql. While Postman confirms that the record has been successfully updated, I am unable to locate where the actual update occurred. No changes seem to be ref ...

Chrome isn't showing the Background Image

I am currently working on coding a basic HTML/CSS page and I want to include a background-image within a div element that links to a URL. Interestingly, my code is functioning properly in Safari (Mac) and Firefox but unfortunately not showing the desired r ...

The Gatsby image background slider is throwing a TypeError because it cannot access the property 'style' of an undefined object

While using gatsby-image-background-slider in my project, I encountered an issue where it throws a TypeError: Cannot read property 'style' of undefined changeIndex src/index.js:111 callback src/index.js:129. Initially, the hero functioned proper ...

Ways to invoke a prop function from the setup method in Vue 3

I encountered the following code: HTML: <p @click="changeForm">Iniciar sesion</p> JS export default { name: "Register", props: { changeForm: Function, }, setup() { //How do I invoke the props change ...

Using Selenium in conjunction with browsermob-proxy to generate new HAR files for redirected web pages

Another interesting scenario I have encountered involves combining Selenium with browsermob-proxy: A new Har is created for the initial page access The initial request can be redirected multiple times And then further redirected by JavaScript For exampl ...

Switching between two identical components can be easily achieved with VueJS

Assume I have a file named foo.vue, which I import into the parent component as components called a and b, and they are displayed based on a variable called show. When switching between components a and b in the parent without setting show = null, various ...

Tips for adjusting the default selection in a second dropdown menu

I have a dilemma with my two dropdown lists, "optionone" and "optiontwo". I am trying to alter the default selected value from "option value=3>3" to option value=3 selected>3 when the user selects 2 from the first dropdown list ("optionone"). <script&g ...

Determine the location based on the preceding parameter of $routeChangeError using AngularJS

I am currently monitoring events of the type $routeChangeError within a run block in my application. $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) { if (!!previous) { console.log(previous); $locati ...

Enhancing collapsible list headers in jquery mobile with checkboxes

Having trouble with a jQuery Mobile website issue. Currently working on a jQuery mobile site that includes a collapsible list (). The client request is to have a checkbox inside the header, allowing users to check items off without needing to open them. T ...

waiting for udp response in node.js using express

Currently, I am diving into the world of node.js programming and have encountered a challenge. While working with express, I came across an issue. When a POST request is made, it triggers a radius authentication process over UDP using the dgram module. Ho ...

Unexpected Object Deconstruction following the useEffect Hook

I encountered a strange issue with object destructuring in react.js, here is the problem I am facing: To begin with, the useEffect function is being used to initialize the rooms variable. const [rooms, setRooms] = useState([]); const _auth = getAuth(app) ...

Activate modifications in a distinct column?

I've been exploring a solution to achieve a similar functionality where clicking or hovering on headings in a column brings up corresponding text in another column. My idea is to use list items with a carousel for this purpose, but I'm facing so ...

Got a not-a-number (NaN) value for the `children` prop in a

Just starting out with React and working on a type racer app. I've encountered an issue while trying to calculate WPM (Words per minute) - the calculation keeps returning 'NaN'. I've double-checked all the variables and ensured there ar ...

Sending blank AJAX data to a PHP function

I am facing a challenge where I need to utilize AJAX to send the ID of an element and a specific value (1,2,3) to a PHP document for validation. Despite successfully logging both values in the console, the PHP file always returns that the data is empty. ...

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

I am facing issues with getting create-react-app to function properly on my computer

While attempting to start my React project, an error log appeared C:\Users\Ezhil & rishii>npx create-react-app firstapp 'rishii\AppData\Roaming\npm\' is not recognized as an internal or external command, opera ...

AngularJs monitoring changes in service

Why does changing the message in the service not affect the displayed message in 1, 2, 3 cases? var app = angular.module('app', []); app.factory('Message', function() { return {message: "why is this message not changing"}; }); app ...

HTML5 footer element is the perfect way to add a

I'm currently working on creating a footer that stretches across the entire width of the screen. Originally, I had it nested within the body tag which was centered with a width of 825px. To remove this width constraint, I moved the footer under the ht ...

The Google API is experiencing issues when using input that has been added on

Situation: In my attempt to integrate a Google address search feature into an online shopping website, I encountered a challenge. I don't have direct access to the website's HTML code, but I can insert code snippets in the header, footer, and in ...

Create a pair of divs on your webpage that users can drag around using HTML5

Hello to all HTML5 developers! I am currently facing an issue where I am attempting to designate two separate divs as dragable areas for incoming files. Unfortunately, it seems that only one of them can be active at a time. How can I adjust my code so th ...