'how to edit user data and pass values to form inside modal using reactjs?

When clicking on the edit button of the table, I need to get the user's values and move to the form that is inside the modal. Then save/replace the data in the table. How to make? If anyone knows how to solve this problem please help me, I don't know how to do it!

App.js

import './App.css';
import Navbar from './components/Navbar';
import Home from './components/pages/Home/Home';
import ListarPacientesHome from './components/pages/ListarPacientes/ListarPacientes';
import Sobre from './components/pages/Sobre/Sobre';
import Cadastrar from './components/pages/Cadastrar/Cadastrar'
import React, { useState, useEffect } from 'react'

import {
  BrowserRouter,
  Routes,
  Route,
} from "react-router-dom";

const App = () => {
  const storage = JSON.parse(localStorage.getItem("pacientes")); // pega a string JSON e converte para objeto JavaScript
  const [pacientes, setPacientes] = useState(storage);
  // const [pacienteEdit, setPacienteEdit] = useState(false); // para editar paciente
  useEffect(() => {
    localStorage.setItem("pacientes", JSON.stringify(pacientes));//converting to string JSON

}, [pacientes]);

  return (
    <BrowserRouter>
      <Navbar />
      <Routes>
        <Route exact path="/" element={<Home />}>
        </Route>
        <Route exact path="/cadastrar" element={<Cadastrar pacientes={pacientes} setPacientes={setPacientes} />}>
        </Route>
        <Route exact path="/listar" element={<ListarPacientesHome pacientes={pacientes} setPacientes={setPacientes}/>}>
        </Route>
        <Route exact path="/sobre" element={<Sobre />}>
        </Route>
      </Routes>
    </BrowserRouter>
  );
}
export default App;

ModalEdit.js

import React, { useState } from "react";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Modal from "@mui/material/Modal";
import styled from "styled-components";

const NewBox = styled(Box)(({ theme }) => ({
    width: "50%",
    margin: "auto"
}));
const style = {
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    bgcolor: "background.paper",
    border: "2px solid #000",
    boxShadow: 24,
    p: 4,
    position: "relative"
};

const buttonClose = {
    position: "absolute",
    right: "0",
    top: "0"
};

const ModalFormulario = () => {
    const [open, setOpen] = useState({
        show: false
    });
    const handleOpen = () => {
        setOpen({
            show: true
        });
    };
    const handleClose = () => {
        setOpen({
            show: false
        });
    };
    return (
        <div>
            <Button onClick={handleOpen}>Edit</Button>
            <Modal
                open={open.show}
                aria-labelledby="modal-modal-title"
                aria-describedby="modal-modal-description"
            >
                <NewBox sx={style}>
                    <Box sx={buttonClose}>
                        <button
                            style={{
                                border: "none",
                                cursor: "pointer",
                                backgroundColor: "transparent"
                            }}
                            onClick={handleClose}
                        >
                            X
                        </button>
                    </Box>
                    <Typography id="modal-modal-title" variant="h6" component="h2">
                        Editar paciente
                    </Typography>
                    <Typography id="modal-modal-description" sx={{ mt: 2 }}>
                        Duis mollis, est non commodo luctus, nisi erat porttitor ligula.
                    </Typography>
                </NewBox>
            </Modal>
        </div>
    );
}

export default ModalFormulario

Table code with users - ListUser.js

import React, { useState } from 'react'
import styled from 'styled-components'
import TextField from '@mui/material/TextField';
import Box from '@mui/material/Box';
import TotalPacientes from '../../TotalPacientes/TotalPacientes';
import Alert from '@mui/material/Alert';
import { Container } from 'semantic-ui-react';

const Table = styled.table`
border-collapse: collapse;
td, th {
  border: 1px solid #bbb;
  text-align: center;
  padding: 1rem;
}
tr:nth-child(even) {
  background-color: #eee;
}
tr.status-paciente{
  text-decoration: line-through solid  #d60e0e;
  opacity: 0.5;
}
`
const Button = styled.button`
border: none;
cursor: pointer;
background-color: transparent;
`

const ListarPacientes = ({ pacientes, setPacientes }) => {
  const [searchInput, setSearchInput] = useState();
  const [remove, setRemove] = useState({
    success: false,
    menssageRemove: '',
  });
  const FilteredPatientsByName =
    !searchInput ? pacientes : pacientes.filter(paciente => paciente.nome.toLowerCase().includes(searchInput.toLowerCase()))

  const handleSearch = (event) => {
    setSearchInput(event.target.value);
  };
  const removePaciente = (idToDelete) => {
    const confirmarExclusao = window.confirm("Confirmar exclusão?");
    if (confirmarExclusao) {
      const newPatient = [...pacientes];
      newPatient.splice(idToDelete, 1);
      setPacientes(newPatient);
      setRemove({
        success: true,
        menssageRemove: 'Paciente removido',
      });
      setTimeout(() => setRemove({ success: false, menssageRemove: '' }), 3000);
    }
  };
  const handleDisablePatientClick = (paciente) => {
    setPacientes(
      pacientes.map((item) =>
        item.id === paciente.id ? { ...item, status: !item.status } : item
      )
    );
  }
  return (
    <Container>
      <div style={{ display: "flex", alignItems: "center", flexDirection: 'column' }}>
        <h1>Listar Pacientes</h1>
        <Box style={{ marginBottom: '2rem' }}>
          <TextField value={searchInput} label="Pesquisar paciente" variant="outlined" onChange={handleSearch} name='search' type='text' id='search' />
        </Box>
        <Table style={{ border: '1' }}>
          <thead>
            <tr style={{ padding: '0 1rem' }}>
              <th>Nome</th>
              <th>Data de nascimento</th>
              <th>CPF</th>
              <th>Gênero</th>
              <th>Endereço</th>
              <th>Status</th>
              <th>Ações</th>
            </tr>
          </thead>
          <tbody>
            {pacientes.length > 0 ? (
              FilteredPatientsByName.map((paciente, index) => (
                <tr key={paciente.id} className={`${paciente.status ? "" : "status-paciente"}`}>
                  <td>{paciente.nome}</td>
                  <td>{paciente.dataDeNascimento}</td>
                  <td>{paciente.cpf}</td>
                  <td>{paciente.sexo}</td>
                  <td>{paciente.endereco}</td>
                  <td><Button onClick={() => handleDisablePatientClick(paciente)} style={{ backgroundColor: '#16ab14', padding: '5px', fontWeight: '600' }}>{paciente.status === true ? 'Ativo' : 'Inativo'}</Button></td>
                  <td>
                    <Box style={{ display: "flex", justifyContent: "space-between" }}>
                      <Button
                        className="button muted-button"
                        onClick={() => removePaciente(index)}
                      >
                        <i
                          style={{ color: 'red' }}
                          className="fa-solid fa-trash fa-xl"
                        />
                      </Button>
                      <Button
                        className="button muted-button"
                      >
                        <i
                          style={{ color: 'orange' }}
                          className="fa-solid fa-pen-to-square fa-xl"
                        />
                      </Button>
                    </Box>
                  </td>
                </tr>
              ))
            ) : (
              <Alert style={{ marginTop: '2rem' }} severity="info">Nenhum usuário para <strong>listar ou filtrar</strong></Alert>
            )}
          </tbody>
        </Table>
        <TotalPacientes
          listarTotalPaciente={pacientes.length}
          listarStatus={pacientes.filter((paciente) => paciente.status).length}>
        </TotalPacientes>
        <Box style={{ marginTop: '2rem' }}>
          {remove.success === true ?
            <Alert severity="success">Paciente removido</Alert>
            : ''}
        </Box>
      </div>
    </Container>
  )
}

export default ListarPacientes

User List

Code Submit.js

import React, { useState, useEffect } from 'react'
import './Cadastrar.css'
import { Form } from 'semantic-ui-react'
import { Button } from '@material-ui/core';
import Container from '@material-ui/core/Container';
import Box from '@mui/material/Box';

const Cadastrar = ({ pacientes, setPacientes }) => {
    const [open, setOpen] = useState(true);
    const [pacienteInfo, setPacienteInfo] = useState({
        nome: "",
        dataDeNascimento: "",
        cpf: "",
        sexo: "",
        endereco: "",
    });
    const [disable, setDisable] = useState(false);
    const [mensage, setMensage] = useState({
        messageCpf: "",
        mensageSubmit: ''
    });
    const handleFieldChange = (event) => {
        const { name, value } = event.target;
        setPacienteInfo({
            ...pacienteInfo,
            [name]: value
        });
    }
    const onFormSubmit = (event) => {
        event.preventDefault();
        if (!pacienteInfo) return;
        setPacientes([...pacientes, {
            id: Date.now(),
            nome: pacienteInfo.nome.trim(),
            dataDeNascimento: pacienteInfo.dataDeNascimento,
            cpf: pacienteInfo.cpf,
            sexo: pacienteInfo.sexo,
            endereco: pacienteInfo.endereco.trim(),
            status: true
        }]);
        setPacienteInfo({ nome: '', dataDeNascimento: '', cpf: '', sexo: '', endereco: '' });
    };
    //Desabilita botao enviar se existir cpf duplicado
    useEffect(() => {
        setDisable(pacientes.some(item => item.cpf === pacienteInfo.cpf))
        const ifExistCpf = () => {
            const filterCpf = pacientes.some(item => item.cpf === pacienteInfo.cpf);
            if (filterCpf === true) {
                setMensage({
                    messageCpf: "Esse CPF já existe",
                });
            } else {
                setMensage({
                    messageCpf: '',
                });
            }
        }
        ifExistCpf();
    }, [pacientes, pacienteInfo]);
    return (
        <Container maxWidth="sm" style={{ display: "flex", flexDirection: 'column', alignItems: 'center' }}>
            <Box>
                <h1>Cadastrar paciente</h1>
            </Box>
            <Form onSubmit={onFormSubmit} className='attached fluid segment'>
                <Form.Field>
                    <label htmlFor='nome'>Nome</label>
                    <input onChange={handleFieldChange} value={pacienteInfo.nome} name='nome' type='text' id='nome' placeholder="Insira seu nome" maxLength='60' pattern="[a-zA-Z][a-zA-Z\s]*" title='Não é permite espaço em branco' required />
                </Form.Field>
                <Form.Field>
                    <label className="margin-top" htmlFor='dataDeNascimento'>Data de Nascimento</label>
                    <input onChange={handleFieldChange} value={pacienteInfo.dataDeNascimento} name='dataDeNascimento' type='text' id='dataDeNascimento' placeholder="Formato: dd/mm/aaaa" pattern='(0[1-9]|[12][0-9]|3[01])[/](0[1-9]|1[012])[/](19|20)\d\d' title='É permitido ano entre 1900 e 2099' required />
                </Form.Field>
                <Form.Field>
                    <label className="margin-top" htmlFor='cpf'>CPF</label>
                    <input onChange={handleFieldChange} value={pacienteInfo.cpf} name='cpf' type='text' id='cpf' placeholder="Formato: xxx.xxx.xxx-xx" pattern="\d{3}\.\d{3}\.\d{3}-\d{2}" required />
                    <small>{mensage.messageCpf}</small>
                </Form.Field>
                <Form.Field>
                    <label className="margin-top" htmlFor='sexo'>Gênero</label>
                    <select onChange={handleFieldChange} value={pacienteInfo.sexo} id='sexo' name='sexo' required>
                        <option value='' disabled>Escolha uma opção...</option>
                        <option value="Femenino">Feminino</option>
                        <option value="Masculino">Masculino</option>
                        <option value="Não Binario">Não-binário</option>
                        <option value="Outros">Outros</option>
                        <option value="Não Informado">Prefiro não informar</option>
                    </select>
                </Form.Field>
                <Form.Field>
                    <label className="label" htmlFor='endereco'>Endereço</label>
                    <input onChange={handleFieldChange} value={pacienteInfo.endereco} name='endereco' type='text' id='endereco' placeholder='Insira seu endereço' />
                </Form.Field>
                <Box className="margin-top" style={{ display: 'flex', justifyContent: 'space-around' }}>
                    <Button type='submit' size="small" variant="contained" color="primary" disabled={disable}>Enviar</Button>
                    <Button type='reset' size="small" variant="outlined">Limpar</Button>
                </Box>
            </Form>
        </Container>

    )
}
export default Cadastrar

Print form

enter image description here enter image description here Expected result



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source