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
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>