Attempting to display items using the map method, pulling in text from an array

I am working with an array state that tracks the text entered by the user in a text field. My goal is to display this text within a component so users can see what they have previously entered. However, I am facing an issue with my Hashtags component when attempting to render it using a ternary operator.

import React from "react";
import Avatar from "@material-ui/core/Avatar";
import Chip from "@material-ui/core/Chip";
import TextField from "@material-ui/core/TextField";
import { useState } from "react";
import Button from "@material-ui/core/Button";

export default function OutlinedChips() {
  const [hashtag, setHashtag] = useState("");
  const [numberOfHashtags, setNumberOfHashtags] = useState(0);
  const [arrayOfHashtags, addHashtag] = useState([]);
  const handleDelete = () => {
    console.info("You clicked the delete icon.");
  };
  const handleHashtagChange = event => setHashtag(event.target.value);

  const handleClick = () => {
    console.info("You clicked the Chip.");
  };
  const newHashtag = () => {
    if (numberOfHashtags < 3) {
      setNumberOfHashtags(numberOfHashtags + 1);
      addHashtag(arrayOfHashtags => arrayOfHashtags.concat(hashtag));
    } else {
      console.log("Too much hashtags");
    }
  };
  const Hashtags = arrayOfHashtags.map(h => (
    <Chip
      size="small"
      avatar={<Avatar>#</Avatar>}
      label={h}
      onDelete={handleDelete}
    />
  ));
  console.log(arrayOfHashtags);
  return (
    <div>
      <TextField
        size="small"
        inputProps={{
          style: { fontSize: 15 }
        }}
        id="outlined-multiline-static"
        multiline
        rows={1}
        placeholder="Description"
        variant="outlined"
        value={hashtag}
        onChange={handleHashtagChange}
      />
      <Button color="primary" onClick={newHashtag}>
        Create!
      </Button>
      {numberOfHashtags > 0 ? <Hashtags /> : ""}
    </div>
  );
}

You can find the sandbox for this code here

Answer №1

In my opinion, the proper way to handle Hashtags is by using this syntax:

{numberOfHashtags > 0 ? Hashtags : ""}

It's important to remember that your Hashtags should return an array, not a component, so it can't be called like one.

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

Managing mouse click events in jQuery

Here on SO, I successfully implemented the mouse down handler. Now, my goal is to separate these functions into their own file named test.js. Within test.js, the code looks like this: function handleMouseDown(e) { console.log('handleMouseDown&ap ...

Ways to make the background color white in Bootstrap 5

Can someone assist me in changing the background color of my portfolio to white? I attempted to use global CSS, but the black background on both sides of the page is preventing the change. return ( <> <Navbar /> <main className= ...

I have been utilizing ESBuild to compile JavaScript code for browser usage. However, I encountered an issue when trying to import CSS as I received an error message stating "Unexpected '.'". Can anyone provide guidance on how to resolve this issue?

I am currently developing a JavaScript notebook that operates within the browser environment. To compile my code, I have chosen to utilize ESBuild. My primary objective is to enable the handling of CSS imports such as <import 'bulma/css/bulma.css&a ...

The challenge with Normalizr library in Redux and how to address it

I am currently attempting to utilize the Normalizr library by Paul Armstrong in order to flatten the Redux state. Below are the schema definitions: import { normalize, schema } from 'normalizr' const fooSchema = new schema.Entity('foos&apo ...

React Native can sometimes encounter issues where the state is null, but fear not, as setState is

It seems that the asynchronous nature of this.setState({ ... }) is causing some issues with my application state. I suspect this might be related to a problem I am facing. The issue arises when trying to display a dialog popup to users upon sending a push ...

Encountering a null value after making changes to the state in Reactjs

I'm currently working on a drag-and-drop web application using reactjs. The issue I'm encountering is that when I initiate the drag action, it triggers the handleDragStart function to update the state variable called selectedCard. However, when I ...

Selecting a value from a populated dropdown and checking the corresponding checkbox in SQL Server

There are 8 checkboxes in this example: <table style="border-collapse: collapse; width: 100%;" border="1"> <tbody> <tr style="height: 21px;"> <td style="width: 25%; height: 21px;"><strong>Technology</strong& ...

Local Storage State Persistence Issue with React Checkbox Component

I am currently working on a React component that features a checkbox. My goal is to have the checkbox toggle between on and off states and save this state in local storage so that even when navigating to another page, the toggle will remain in its previous ...

Is there a way for the React select component to adjust its width automatically based on the label size?

After defining a React select component, it looks like this: <FormControl> <InputLabel id="demo-simple-select-label">Age</InputLabel> <Select labelId="demo-simple-select-label" id=&quo ...

How to access a grandchild's property using a string in JavaScript

Is there a way to access a property nested deep within an object when creating a custom sorting function? I am attempting to implement a sort function that can sort an array based on a specific criteria. const data = [ { a: { b: { c: 2 } ...

The Date Filter is causing a glitch in formatting the date value

I have a variable called dateSubmitted with the value of "dateSubmitted": "07-09-20:11:03:30" Currently, I am utilizing Angular Version 7 Within my HTML code, I am using the date filter to format the date like so: <td> {{element.dateSubmi ...

Guide on leveraging a private GitHub repository as a yarn dependency without installing internal dependencies

Recently, I have been attempting to incorporate a private GitHub repository as a dependency within multiple repositories at my workplace. Within the primary package.json file, our dependency is outlined as follows: "mycompany-models": "https://github.com ...

Understanding the repetition of the X axis in Recharts for ReactJS

I am facing an issue where the X axis on my graph is repeating three times for each month of the year. I have tried adding my data, but the duplication persists. Can anyone provide insight on how to correct this error? What am I doing wrong? Below is a mi ...

Determine the scroll location using NextJS

I'm trying to determine if the user has scrolled in order to update the UI using NextJS. I have come across various examples with similar code, such as this one: const [scrollY, setScrollY] = useState(0); const onScroll = (event) => { cons ...

Live Edit API

Currently, I am developing an application that requires near real-time collaborative editing capabilities for documents, similar to the functionality found in Google Documents. Since I am a beginner in this area, I would greatly appreciate any information ...

Automatically append a version number to destination output files using the Grunt task runner

We have a package.json file that contains our version number, like this: { name: "myproject" version: "2.0" } The objective is to dynamically insert the version number from the package.json file into the output files. Instead of manually updating ...

Creating a dynamic sidebar based on roles in AngularJS

I'm looking to create a dynamic sidebar based on the user's role, which is stored in $rootScope.login. However, I'm unsure of how to integrate it into template.js. Below is my JavaScript code and I'm still relatively new to AngularJS. ...

Unexpected issue with PHP/Ajax/JQuery response functionality

I am experiencing an issue with my index.php file. Here is the code: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="ajax.js"></script ...

Tips for perfectly aligning all elements in a row within a card design

Hi there, I'm trying to figure out how to align the content of this card in a single row instead of stacked on top of each other. Here's the code snippet: <div class="container"> <form onSubmit={submitHandler}> ...

"Successful implementation of Ajax function in local environment but encountering issues when running online

I am facing an issue with my AJAX function. It works perfectly fine on my local server but does not return anything when I move it to my online server. Below is the code snippet: This is the part of the page where I call the showEspece() function: echo ...