React edit div content function is not operating properly as anticipated

Snippet of React code

class LoginIdCard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      website: "",
      username: "",
      password: "",
      editMode: false,
    };
  }
  handleEdit = (fieldName, val) => {
    this.setState({
      [fieldName]: val,
    });
  };
  creatLoginCardItem() {
    const { logins } = this.props;
    const { editMode } = this.state;

    return logins.map((logins) => {
      return (
        <div className="card">
          <button onClick={() => this.handleEdit("editMode", true)}>
            edit
          </button>
          <p>{logins.website}</p>
          <p>{logins.username}</p>
          <p>{logins.password}</p>
        </div>
      );
    });
  }
  render() {
    const { editMode } = this.state;
    return <>{editMode ? <input /> : this.creatLoginCardItem()}</>;
  }
}

export default LoginIdCard;

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

The above code snippet generates a cards component that can be viewed here: web-app rendering

I aim to make the content within each card editable by clicking the edit button and using a form input. However, currently, all cards are replaced by a form when the edit button is clicked. I'm looking for a solution where each card can be edited individually and then saved to the store.

Answer №1

Your approach needs a bit of tweaking. Ensuring each login card has its own state requires setting the state individually for each one.

  1. Start by creating a new component called LoginCardItem, which will encompass all the state logic currently in use (e.g., this.state.editMode, ...)

  2. Rename your current LoginIdCard to something like LoginCardOverview to indicate that it serves as an overview.

  3. In the LoginCardOverview component, you can loop through the logins.

Return logins.map((login) => <LoginCardItem />)

This way, every LoginCardItem will maintain its own state.

To update the input value afterward, adjust the state of the input using this method:

<input onChange={(e) => this.setState({name: e.target.value})} />

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

Encountering a CORS error while trying to fetch a YouTube page in React

Can someone help me extract the HTML markup of a YouTube video page? Below is the code I have so far: async function get_subtitles(video_id: string): Promise<string> { if (video_id.includes('https://') || video_id.includes('http:// ...

The alignment of the Div element is incorrect following a fixed video in bootstrap

When I place a div after the video, the div appears on top of the video instead of after it. Additionally, when I change min-width: 100% to width: 100%, the content appears before the video when I resize the browser. body{ font-family: 'Mina', ...

What is the appropriate way to notify Gulp when a task has been completed?

I have been working on developing a gulp plugin that counts the number of files in the stream. Taking inspiration from a helpful thread on Stack Overflow (source), I started implementing the following code: function count() { var count = 0; function ...

how can JavaScript be used to retrieve an object based on a condition from an array of objects and an ArrayList

My JavaScript challenge involves working with an array of objects called arrobj and a list called prgList. The goal is to extract the names from arrobj based on the programs listed in prgList. If the program exists in arrobj, it should be displayed accor ...

In Sequelize, the "afterBulkCreate" hook consistently provides the most recent values in the _previousDataValues, particularly when utilizing updateOnDuplicate to modify specific columns

Table.addHook('afterBulkCreate' , async (params , options) => { console.log("Table.afterBulkCreate ~ params:", params , options) }) const st1 = await Table.bulkCreate(params, { updateOnDuplicate: ["metrics", ...

"Techniques for incorporating a screen in Angular application (Switching between Edit and View modes) upon user interaction

We are currently working on a screen that requires the following development: This screen will have the following features: When clicking on a button, the fields should become editable. In the image provided, there is some repeated data, but in our case, ...

Overlapping HTML5 Videos with Interactive Buttons

I'm currently working with a website using HTML5 Video to display a video. I want the video to overlap, but I also want to include a button/link that will redirect users to more information when clicked. For example: .outer-container { border: ...

Styling text over an image when hovering with CSS and HTML

I have successfully implemented a functionality, but I am looking to enhance the appearance of the text displayed when an image is hovered over. Below is the current code snippet: .ecommerce-categories [class^=col-] > a:before { content: attr(data- ...

Ensure that the form is validated even when setState is not executed immediately

I am currently working on a form in React and I am facing an issue with validation. When the Submit Form button is clicked without filling in the input fields, an error should be displayed. This part is functioning correctly. However, even when the fields ...

Navbar Username in Next.js with Typescript and Supabase Integration

I'm currently facing an issue with retrieving the username of a user to display in my navbar. The desired username is stored in the "username" column of the table called "profiles" in my Supabase database. However, the data that's populating the ...

Utilizing TypeScript with React to dynamically select which component to render

My task seemed simple at first: to render a React component based on its name/type. Here is an example of how it is used: // WidgetsContainer.ts // components have a difference in props shape! const componentsData = [ { type: 'WIDGET_1', ...

Instructions for converting SCSS to CSS and storing the CSS code as a string in a variable

I am currently developing a Single Page Application (SPA) using Vue (specifically Quasar), and I have the following requirements: Load the contents of a CSS file into a JavaScript variable or Vue data property dynamically The CSS file should be generated ...

When using pug.compile(), the template files cannot be located, unlike with res.render()

I am currently developing a NodeJS/Express application and have configured pug as the template engine: const app = express(); app.set('view engine', 'pug'); app.set('views', __dirname + "/public/views"); app.use(express.stat ...

Implementing a Custom <link> Tag in the Head of a Next.js 13 Website

I am striving to incorporate a Safari pinned tab style into my Nextjs13 app. To achieve this, the following tag should be visible in the <head> section: <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#325758&qu ...

Updating field values for all documents with Node and MongoDB

Looking to update a specific field within subdocuments across multiple other documents... Here is an example of the documents: { "_id": { "$oid" : "531cc2410b4ebf000036b2d7" }, "name": "ALMACEN 2", "items": [ { "_id": { "$oid" : "531ed4ca ...

Elevate the React experience by smoothly sliding a fixed navbar upwards when scrolling down, and elegantly sliding it

tl;dr Don't miss the solution at the end! Looking to create a slide up and down effect on a fixed navbar in react? What's the best approach - using refs or the componentDidMount lifecycle hook? hideNav = (navbar) => { const hide = () ...

What is the best way to prevent a page refresh in PHP when data is incomplete?

I have a web page containing two forms, each with an input field and a button named submit1 and submit2. My goal is to use JavaScript to submit the data when content 1 is selected. When content 2 is linked, form2 should be displayed. Upon clicking submit ...

Having difficulty accessing the value of a table td element in HTML using a jQuery selector

When creating a table, I utilize ng-repeat to generate table rows. Whenever the dropdown changes, a function is triggered which applies certain conditions. Based on these conditions, an object is added to an array that is bound to a scope variable. Here i ...

Retrieving the body of a GET request using NodeJS and axios

Let me share my request with you: axios.get(BASE_URI + '/birds/random', {Stuff: "STUFF"}) .then(randBird=>{ const birdData = randBird.data const bird = { age: birdData.age, ...

Is there a way to customize the appearance of the select dropdown without impacting the styling of other Material-UI components, such as the show/hide columns panel?

I am currently working on customizing the appearance of the dropdown panel for my MUI select component. My goal is to achieve a design similar to this: Desired show/hide columns example To accomplish this, I have implemented specific styles within the Mui ...