Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

66
Vistas
how to save an object using a button in reactjs

Currently, I have a WebSocket chat messager using react js, I want to have it save the message object when I click on its associated button so that it will pin it. How do I get a button press to save the object it's associated with?

Currently, I have an array of objects that just stack on top of each other like so:

{messages.map(message => (
        <>
           <tr>
              <td>{message.message}</td>
              <td><button id="pin_button" type="button" >Pin Message</button></td>
           </tr>
        </>
))}

What I want to do is have it when I press that button it will save that object and preferably send it to a WebSocket so that other people can see the message that was pinned

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You should use state.

const [savedMsgs, setSavedMsgs] = useState([]);

<ul className="saved-msgs">
  {savedMsgs.map((msg,i) => <li key={i}>{msg.message}</li>)}
</ul>

<tr>
  <td>{message.message}</td>
  <td>
    <button
      id="pin_button"
      onClick={() => setSavedMsgs([...new Set([...savedMsgs, message])])}
    >
      Pin Message
    </button>
  </td>
</tr>

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos