Home > Enterprise >  Display 'Edited' text when an old state is not equal to a new state with react
Display 'Edited' text when an old state is not equal to a new state with react

Time:10-01

I want to display 'Edited' text when a message is updated like Slack message.

Currently, the default message is '123' and if users type a new message and this new message is not equal to old message (123), I'd like to display the edited text.

Is there any way that I can compare old state and new state?

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [message, setMessage] = useState("123");
  console.log(message);
  return (
    <div className="App">
      <input
        value={message}
        id={message}
        type="text"
        onChange={(e) => setMessage(e.target.value)}
      />
      <p>Display "edited" when message is updated</p>
    </div>
  );
}

CodePudding user response:

In order to compare two values you need to have two values. Keep the original state separate:

const originalState = "123";
const [message, setMessage] = useState(originalState);

Then you can compare the current state to the original state:

{message !== originalState ? <p>Edited</p> : null}

Keep in mind that this will remove the output if the state is changed back to something that matches the original. Sometimes one just wants to track that something was changed in a form, regardless of what. In that case you might have an isDirty flag. For example:

const [isDirty, setIsDirty] = useState(false);
const [message, setMessage] = useState("123");

And any time input changes, you update that flag as well:

onChange={(e) => {
  setMessage(e.target.value);
  setIsDirty(true);
}}

And display the message based on that state:

{isDirty ? <p>Edited</p> : null}
  • Related