Tips for dynamically appending a string to a predefined variable in React

When I was working on creating a text input space using the input type area and utilizing the onChange utility, everything was running smoothly.

Now, my task is to incorporate an emoji bar and insert a specific emoji into the input space upon clicking it. Essentially, I am attempting to append or concatenate the emoji to the variable set as new_chat.

https://i.sstatic.net/XITSMYXc.png

Here are the set variables:

const [chats, setchat] = useState([]);
const [new_chat, set_new_chat] = useState([]);

Functions for managing chats:

function handlechat(event){
        set_new_chat(event.target.value);
    }

    function add_chat(){
        if(new_chat.trim()!=""){
            setchat(c => [...c, {text: new_chat, time: new Date()}]);
            set_new_chat("");
            // settime(t => [...t, new Date()]);
            console.log("new chat added");
        }
    }

Input text code:

<input type="text" id="input_text" value={new_chat} onChange={handlechat}></input>

Snippet for adding emojis:

<div className="emoji_container" style={{fontSize: "1.5em"}} onClick={new_chat.concat('👍')}>👍</div>

I would greatly appreciate any assistance!

I am currently struggling with incorporating emojis from an emoji panel into an input box.

Answer №1

Within your coding, you have successfully showcased how to update the state value of `new_chat` using the `set_new_chat` function in your `handlechat` function. It should follow the same principle when adding an emoji to it - updating state is essentially the same process, regardless of the text being updated.

To achieve this, create a handler that appends the emoji value to the state:

function handleEmoji(emoji){
  set_new_chat(`${new_chat}${emoji}`);
}

Invoke this handler by clicking on the desired emoji:

<div
  className="emoji_container"
  style={{fontSize: "1.5em"}}
  onClick={() => handleEmoji('👍')}
>👍</div>

Answer №2

here is a possible way to do it:

  const ChatApp = () => {
    const [messages, setMessages] = useState([]);
    const [newMessage, setNewMessage] = useState('');

    function handleInput(event) {
      setNewMessage(event.target.value);
    }

    function sendMessage() {
      if (newMessage.trim() !== '') {
        setMessages([...messages, { text: newMessage, time: new Date() }]);
        setNewMessage('');
        console.log('new message added');
      }
    }
    
    return (
      <div>
        <h1>Chat App</h1>
        <input
          type="text"
          value={newMessage}
          onChange={handleInput}
        ></input>
        <button onClick={sendMessage}>Send</button>
        
        <p>Your messages: {messages.map((m) => m.text)}</p>
        <p>Your new message: {newMessage}</p>
      </div>
    );
  };

  export default ChatApp;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to implement a dialog box that displays a website within it, all while keeping my SharePoint site running in the background?

For a while now, I've been working on SharePoint Online and trying to troubleshoot an issue without success. That's why I'm considering starting over with a specific section of my SP site from scratch. My current project involves creating a ...

Issues arise when attempting to instantiate an object within a forEach loop in JavaScript

I've been working on creating a JSON object using data pulled from a MongoDB database. The issue I'm facing is that the last line res.status(200).json(userData) seems to send a response before the data processing is complete, resulting in an emp ...

Tips for adding images using v-for in Vue 3

Having some trouble creating a set of images using a v-for loop, as it seems to be not recognizing the variables inside the tag. The picture is broken and the alt attribute just shows me {{ item.alt }}. Here is my HTML: <section class="our-technolo ...

The perfect method for creating template literals using a function

I have a function that accepts an argument called id and returns a template literal: const generateTemplate = (id) => { return `<div style="box-sizing: border-box; height: 32px; border-bottom: 1px solid #ECECEC; color: #282828; padding: 8px; dis ...

Generate a pair of dates and organize them in chronological order

Working on an application where the database response lacks a direct timestamp, causing data to render differently each day and requiring me to use .reverse() to fix my charts. I aim to implement a permanent solution using sort(), but struggling due to the ...

The Angular MatStepper is unable to detect saved values from two string arrays, although it is able to detect values from a different string array

In my application, there is a MatStepper component that facilitates navigation through the signup flow. A method exists to load cached values when available, causing the MatStepper to skip to Page 2. Subsequently, another method pre-fills the form with the ...

Problem with Material UI Checkbox failing to switch states

I'm a bit confused about the functionality of my checkbox in Material UI. The documentation makes it seem simple, but I'm struggling to get my checkbox to toggle on or off after creating the component. const createCheckBox = (row, checkBoxStatus, ...

Extracting information from a JSON data within an API

How can I retrieve data with a name tag from JSON data using Ajax? The function showCard is not functioning properly when I try to grab data with a name tag. My goal is to display the name of the API data when an img element with the class found is clicked ...

Ways to organize the information within the Ul and Li elements

I need help sorting the data within <ul> and <li> elements using jQuery. Below is a snippet of my code: <ul id="rootUl"> <li> <div id='title'>MSFT</div> <div id='price'>230</d ...

Open multiple accordion sections simultaneously

In my current setup, I have a paginated loop of elements that contains an accordion. The accordion is implemented using angular-ui-bootstrap. <div data-ng-repeat="m in results"> <div class="stuff_in_the_middle"> <accordion id="a ...

`Border radius for the items in Apex Chart's donut chart`

I need help rounding the corners of my donut chart items. Can someone please provide guidance? Here is what I want it to look like And here is what I have created so far const Chart = dynamic(() => import('react-apexcharts'), { ssr: false }) ...

I encountered a slight hiccup while running my React-Node application - everything was smooth sailing until I attempted to import {Provider} from

Here are the dependencies listed in my package.json file: "prop-types": "^15.6.0", "react": "^16.1.0", "react-dom": "^16.1.0", "react-html-email": "^3.0.0", "react-redux": "^4.4.5", "react-route": "^1.0.3", "react-router": "^3.2.0" ...

What occurs when Click events are triggered on an <object> element?

I have set up a div, and inside that container, I embedded an SVG image using object (which I plan to manipulate later...). <div id="click-me"> some random Text <object data="some.svg" /> </div> Next, I added event listeners for t ...

Expanding the visual in a spacious display with the help of ng-carousel from the Bootstrap framework

I have created a slider with multiple images on a website using Angular 4. The slider is displayed in a small area of the webpage and I would like to add a feature where the user can click on an image to view it in a larger screen or window. This could i ...

React - Page Loads with Empty Query Parameters

Seeking assistance with navigation logic in React, I'm encountering an issue that requires some guidance. I have developed a front-end web app using TypeScript, React, and Ionic Framework V5. The app features a standard search box that redirects use ...

Creating a custom color palette with Material UI using ThemeProvider

Attempting to set a custom color for a Button using createMuiTheme and ThemeProvider has been successful with the primary and secondary palettes. However, when trying to utilize an alternate color such as "info", it does not seem to work as expected: http ...

Enhancing the Alignment of a Bootstrap Navbar with CSS

Having trouble centering the listed items (excluding the image and title) in the middle of the navbar. Tried various solutions with no luck! Any suggestions on how to tackle this issue? <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a ...

Ensuring Tab Input Validation in ReactJs with the Help of Form Validator

After browsing through some Q&A, I stumbled upon a thread on the topic of Tabbed form and validation. Although it was close to addressing my issue, it did not provide a solution. I am currently utilizing react-material-ui-form-validator. When multiple ...

Adding a JSX file type to the "File > New" list in WebStorm is a simple process that can enhance your development workflow

Is there a way to customize the items on this list? I am specifically interested in adding a jsx file type to it. https://i.sstatic.net/tfVX0.png ...

Adding Data Definition Language (DDL) statements while making an AJAX call

Is there a way to automatically update the value of a drop-down list whenever a partial view is loaded via an AJAX call? Currently, the AJAX call successfully retrieves the necessary information, but the user still needs to manually change the location val ...