what are some tips for making Material-Ui Chips editable?

I am striving to achieve a similar result like the 4th Example using ReactJS and Material-ui.

I have created something different by overlapping two fields, one being a normal input shown on focus for text editing and the other a chips container displayed on blur for non-editable content.

Can I follow the same approach of placing an input inside each chip, displaying it on click/double-click, and hiding it onBlur?

Answer №1

This code snippet is set up this way and seems to be functioning well, however, feel free to customize the options according to your requirements. There is also a link included at the end.

app.js

class App extends Component {
  state = {
    value: '#Jax #Tom #Zeus',
  };

  handleChange = name => event => {
    this.setState({ [name]: event.target.value });
  };

  render() {
    const { value } = this.state;
    const chips =
      value.length > 0
        ? value
            .trim()
            .split(' ')
            .map(x => {
              if (x.charAt(0) === '#') {
                return x.trim().slice(1);
              } else {
                return '';
              }
            })
            .filter(z => z.length > 0)
        : [];
    return (
      <>
        <div className="container" tabIndex="-1">
          <FormControl className="input">
            <InputLabel htmlFor="chips-input">Chips Input</InputLabel>
            <Input
              id="chips-input"
              value={this.state.value}
              onChange={this.handleChange('value')}
            />
          </FormControl>
          <ChipsContainer chips={chips} />
        </div>
      </>
    );
  }
}

export default App;

ChipsContainer.js

function Chips(props) {
  const { classes } = props;
  return (
    <div className="chip-input">
      <p>Focus blue box</p>
      <div className={classes.root}>
        {props.chips.map((x, idx) => (
          <Chip
            icon={
              idx % 2 === 0 ? (
                <FontAwesomeIcon icon={faDog} spin />
              ) : (
                <FontAwesomeIcon icon={faCat} pulse />
              )
            }
            label={x}
            key={idx}
            className={classes.chip}
            color={idx % 2 === 0 ? 'primary' : 'secondary'}
          />
        ))}
      </div>
    </div>
  );
}

and here is the styling for it

.input {
  visibility: hidden;
  position: absolute;
}

.chip-input {
  visibility: visible;
  position: absolute;
}

.container {
  border: 1px solid blue;
  position: relative;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  &:focus-within {
    .input {
      visibility: visible;
    }
    .chip-input {
      visibility: hidden;
    }
  }
}

Custom Made Material-UI Chips 'Editable'

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

When requiring '@material-ui/icons' in Jest, it returns as undefined

Every time I attempt to use require or require.requireActual in jest to import '@material-ui/icons', jest reports it as undefined. I suspect this could be a bug/issue, as it seems unlikely for any export to be undefined for require. The file bei ...

Troubleshooting the missing next-auth/client module error in a Next.js project

Currently, I am tackling a project in nextjs that involves Prisma and GitHub authentication. However, when I run npm run dev, the project fails to compile. The error is visible in this image: https://i.stack.imgur.com/HC8dc.png How can I troubleshoot and ...

javascript + react - managing state with a combination of different variable types

In my React application, I have this piece of code where the variable items is expected to be an array based on the interface. However, in the initial state, it is set as null because I need it to be initialized that way. I could have used ?Array in the i ...

Tips for utilizing localStorage within server components in the NextJS 13 app directory

Currently, I am utilizing an API call within the Metadata to retrieve information based on the inputted URL. The next/headers are used to access the URL. export async function generateMetadata( { params, searchParams }: MetadataProps, parent: Resolving ...

React is currently in the process of downloading images that were not fetched during

(Update: Initially, I suspected React Router was the cause of this issue. However, after eliminating React Router from the codebase, the problem persists. Therefore, I have extensively revised this inquiry.) Situation: I am dealing with paginated pages th ...

The type '(props: Props) => Element' cannot be assigned to the type 'FunctionComponent<FieldRenderProps<any, HTMLElement>>' in React-final-form

I'm fairly new to using TypeScript, and I am currently working on developing a signUp form with the help of React-Final-Form along with TypeScript. Here is the code snippet that describes my form: import React from "react"; import Button from "@mater ...

Tips for Repurposing a React Table

I am in the process of developing my own react component library to be used across my entire application. At the moment, I have started with a table component which is currently undergoing testing. However, I am facing the challenge of calling the componen ...

When using JavaScript to redirect with window.location, the referrer header is not properly set

Currently, I am attempting to utilize window.location in React to redirect to a third-party page. However, upon making the redirect, the third-party server is not receiving a referrer header from my redirection. Any assistance on resolving this issue wou ...

Why is this text appearing twice on my screen?

When I run the code in my React app and check the console in Chrome, I notice that the response.data[0] is being printed twice. What could be causing this duplication? const fetchData = async () => { return await axios.get(URL) .then((respon ...

Stepper component with a Material-UI twist that adapts to your

Looking to implement a dynamic Material-UI Stepper Component that will appear when the user clicks on ADD. The issue arises when interacting with the stepper components, as clicking on NEXT, BACK, or SKIP causes all added stepper components to move simulta ...

Libraries that automatically suggest options for integrating objects described by JSON schema

We are currently developing a platform with an email templating feature. Users can insert objects and variables into their emails using json-schema. Although we are not the first ones to work on this, our research has not turned up many libraries that cou ...

What is causing the issue with Shallow routing in Nextjs?

I've been experimenting with Shallow routing in Next.js to update the state in the URL without actually navigating to a new page, but I'm encountering unexpected behavior. In the scenario outlined below, I start on the home page using the URL: l ...

The sequence of execution in React hooks with Typescript

I'm having difficulty implementing a language switching feature. On the home page of my app located at /, it should retrieve a previously set preference from localStorage called 'preferredLanguage'. If no preference is found, it should defau ...

Tips for retrieving hidden columns in a datagrid

Currently, I am utilizing the premium version of material-ui's DataGrid known as x-Grid. This feature enables users to toggle between hiding and showing columns either through the column options menu or the Columns Panel on the toolbar. My objective: ...

Error: The dataProvider function toJSON is not recognized

import restProvider from 'ra-data-simple-rest' const dataProvider= process.env.REACT_APP_API+'/api/link' <Admin dataProvider={restProvider(dataProvider) }> <Resource name='endpoint' options={{label:'MyLab ...

Discovering the method to access the on-hover element/color of Material UI's text field bottom border

I am having some trouble customizing the textfield component in Material UI. Before I move my mouse over the field, I can change the bottom border color. After clicking on the field, I can also modify its color. However, when my mouse hovers over the fiel ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

Error encountered: No matching overload found for MUI styled TypeScript

I am encountering an issue: No overload matches this call. Looking for a solution to fix this problem. I am attempting to design a customized button. While I have successfully created the button, I am facing the aforementioned error. Below is my code ...

Editable Table Component in React

I've developed a React table as shown below: const CustomTable = ({content}) => { return ( <table className="table table-bordered"> <thead> <tr> <th>Quantity</ ...

Attempting to transfer a username String from the client to the server using React and Typescript

I am working on a project where I need to send the username of a logged-in user from the Client to the Server as a string. Currently, I am able to successfully send an image file, but now I also need to send a string along with it. What I aim to do is repl ...