Home > Blockchain >  React: Using the same form for create and update record
React: Using the same form for create and update record

Time:02-02

I am new in ReactJS and build a Create form for record. On the other hand, now I need to create an Update form and I am wondering an elegant solution and apply it for the next projects as well.

I checked several projects and examples, but could not be sure regarding the following issues:

1. Can I use the same form for Create and Update? Is there a proper example for that?

2. When using Update form, I thought passing the record to Update form via props and then populate these values to the related controls. The rest seems to be similar to Create form, right? Or is there a specific approach for this purpose?

3. How can I pass record as prop to the Update form (I open it via Route, then should I pass a query param, etc?)

CodePudding user response:

You can make a separate Form component that takes props and sets them as initial state, then updates its local state on edit. The form also takes a callback on submit. Now,

  1. When you want to create a new form you do not pass any data except the create callback
  2. when you want to update data, you pass props and the update callback.

Here's an example sandbox for reference - https://codesandbox.io/s/happy-thunder-0pjtvr?file=/src/App.js.

The form component

const Form = ({ name = "", email = "", callback }) => {
  const [data, setData] = useState({ name: name, email });
  const handleSubmit = (ev) => {
    ev.preventDefault();
    callback(data);
  };
  useEffect(() => {
    setData({ name, email });
  }, [name, email]);
  return (
    <form onSubmit={handleSubmit}>
      <input
        value={data.name}
        onChange={(ev) => setData({ ...data, name: ev.target.value })}
        name="name"
        placeholder="Name"
      />
      <input
        value={data.email}
        onChange={(ev) => setData({ ...data, email: ev.target.value })}
        name="email"
        placeholder="Email"
      />
      <button>Submit</button>
    </form>
  );
};
  • Related