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

Tips for ensuring that Breadcrumbs are displayed properly with the noWrap feature

I am currently working on making the MUI component Breadcrumbs responsive. The issue I am facing is that when the Breadcrumbs component fills up all available space, the items shrink and use ellipsis like a Typography component with the noWrap property se ...

The functionality of RegExp is not as expected in this specific case, even though it works correctly in all

I am new to Node.js and currently transitioning from a PHP background, eager to learn more about it. My challenge involves using the following Regular Expression: /([A-Z]{2,})+/gim (identifying two or more consecutive letters). The string I am working w ...

Exploring Submit Validation Implementation with Material UI and Redux-Form

Currently I am utilizing Redux Form and material UI in order to create a registration page. In my onSubmit function, I am incorporating the fetch API to send a POST request to the server. Should there be any errors related to the server (such as a duplicat ...

Using AngularJS to dynamically bind HTML content based on a variable’s value

I am trying to dynamically display an image of a man or a woman on a scene, depending on the gender of the person logged into my website. The ng-bind-html directive is working fine when I define "imageToLoad" statically. However, it fails when I try to gen ...

Tips for efficiently waiting for the outcome in a unified function for multiple callbacks within node.js

Perhaps the question title is not the most appropriate, but let me explain what I am trying to achieve in my code // First Callback Function connection_db.query(get_measure_query,function(err,user_data1){ if(err){ // throw err; ...

Bower fails to add components during installation

For my current project, I have been utilizing bower locally to handle JavaScript dependencies with no issues. However, today I encountered a problem when attempting to initiate a new project by reusing code from previous projects. Specifically, I tried to ...

React-Toolbox: Attempting to horizontally align the Cards side by side

When working with React-Toolbox, I encountered an issue with aligning Card elements horizontally. I attempted using display: inline-block, which successfully separated them into three distinct cards as desired. However, they did not align next to one ano ...

How do I resolve the jQuery error "unable to find function url.indexOf" when working with Vide?

I had previously asked a question regarding the use of the Vide plugin for playing background videos on my website, which can be found here. However, I am now encountering an error that is puzzling me: https://i.stack.imgur.com/UDFuU.png I am unsure abo ...

What is the process for querying the Prisma API to retrieve the present server timestamp?

I'm struggling to assign the current timestamp to a database field. Although the Prisma Schema Reference allows for setting a field to the current time using now(), it seems that the Prisma API does not support this function. Is there a method I can ...

What is the best way to hide a custom contextmenu in AngularJs?

I created a custom contextmenu directive using AngularJs. However, I am facing an issue where the menu is supposed to close when I click anywhere on the page except for the custom menu itself. Although I have added a click function to the document to achie ...

Filtering JSON Data at Multiple Levels

I am facing an issue with my JSON data: this.state = { projects: [{ id: 10, name: "Project 10", runTimes: [{ id: 186, name: "Do Homeworks", start: "2020-W01", end: "2020-W09", project: 10, users: [{ ...

Multer failing to generate file during request process

My current setup involves a router and multer middleware, but I'm facing an issue where the file requested is not being created. As a result, req.file always remains undefined. const multer = require('multer'); let storage = multe ...

Is it a good idea to relocate the document.ready function into its own JavaScript function?

Can the following code be placed inside a separate JavaScript function within a jQuery document.ready, allowing it to be called like any other JavaScript function? <script type="text/javascript"> $(document).ready(function() { $('div#infoi ...

Enhancing the camera functionality of the HTML <input> tag for iPhone and Android devices

I am currently working on a mobile web application that requires access to the device's camera. I am aware that this can be achieved using the following code: <input type="file" accept="image/*" capture="camera" /> The code snippet above suc ...

What causes fs to produce an error when routing to a new page, yet refreshing the page resolves the issue?

Concern: I have developed a NextJs application with 4 input fields, each connected to a predefined options list read in as a json file within the project. The user can select two fields and then proceed to a search page by clicking a button. From the sear ...

Show a pop-up form when a user focuses on it using React

Hello, I have been looking for a way to create an overlay with a form that appears when a specific input field is clicked. I am trying to achieve this using React. Can someone please advise me on how to accomplish this? Here is my code import React, { Co ...

Is it true that Material-UI @next does not accommodate props-based styling?

Material-UI@next has introduced a shift from LESS-based styling to CSS-to-JS-based styling. However, the component demos on Material-UI's website seem to overlook props-based styling. I am facing an issue while trying to create divs with specific abso ...

Is it permissible to generate data in PDF format directly from the frontend?

Within my application, there exists a search form that produces paginated results in the back-end. Occasionally, searches yield thousands of results. A new feature request has been made to allow for exporting search results in PDF format. I am wondering ...

flatpickr allows you to synchronize the dates of two date pickers by setting the date of the second one to match the date

Currently utilizing flatpikr from . I'm looking to have the initial date of the return picker set to the same date as the outbound picker upon closing the outbound picker. The code I've written achieves this functionality, but there's an iss ...

Visual Gallery Component in React Native

Looking for advice on incorporating image sheets into a react native project. Specifically, I'm wondering if it's possible to define frame dimensions and utilize a single image to showcase multiple icons. Take a look at this image sheet for refer ...