Languages
[Edit]
EN

React - editable table cell after mouse click

8 points
Created by:
Frida-Timms
667

In this short article we would like to show you how to create in React editable cell on mouse click.

The solution presented in the article switches text into editable input element after user clicks on them. To accep new value Ok button is attached to each cell. That kind of approach can be used with tables to let user edit tables.

Editable table cells in React.
Editable table cells in React.

Notes:

  • read this article to know how to change state from props,
  • read this article to see how to use editable cell inside editable table.

Quick solution:  

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const itemStyle = {
  	padding: '2px',
	border: '1px solid silver',
  	fontFamily: 'Arial',
  	fontSize: '13px',
  	display: 'flex'
};

const textStyle = {
  	...itemStyle,
  	padding: '5px 4px',
};

const inputStyle = {
  	padding: '0',
	flex: '1',
  	fontFamily: 'Arial',
  	fontSize: '13px'
};

const buttonStyle = {
  	flex: 'none'
};

const Cell = ({value, onChange}) => {
  	const [mode, setMode] = React.useState('read');
  	const [text, setText] = React.useState(value ?? '');
    React.useEffect(() => {
    	setText(value);
  	}, [value]); // <--- when value is changed text state is changed too
	if (mode === 'edit') {
        const handleInputChange = (e) => {
    		setText(e.target.value);
        };
        const handleSaveClick = () => {
            setMode('read');
          	if (onChange) {
          		onChange(text);
            }
        };
        return (
          <div style={itemStyle}>
            <input type="text" value={text}
                   style={inputStyle} onChange={handleInputChange} />
            <button style={buttonStyle} onClick={handleSaveClick}>Ok</button>
          </div>
        );
    }
  	if (mode === 'read') {
        const handleEditClick = () => {
            setMode('edit');
        };
        return (
          <div style={textStyle} onClick={handleEditClick}>{text}</div>
        );
    }
  	return null;
};

// Usage example:

const App = () => {
  const [values, setValues] = React.useState(['Text 1', 'Text 2', 'Text 2']);
  console.log(...values);
  return (
    <table style={{width: '250px'}}>
      <tbody>
      {values.map((value, index) => {
        const handleChange = value => {
            // map() method used to update indicated value with state copy
        	setValues(values.map((v, i) => index === i ? value : v));
        };
		return (
          <tr key={index}>
            <td><Cell value={value} onChange={handleChange} /></td>
          </tr>
        );
      })}
      </tbody>
    </table>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App/>, root );
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join