Home > Blockchain >  How to add the component which allows adding an article to a list
How to add the component which allows adding an article to a list

Time:12-13

I need to add the ListArticle component which allows adding an article to a list.

import React, { useState } from "react";
export default function ListArticle() {
  const [id, setId] = useState(0);
  const [designation, setDesignation] = useState("");
  const [prix, setPrix] = useState(0);
  const [Article, setArticle] = useState([]);
  const handlerOnChangeId = (e) => {
    setId(e.target.value);
  };
  const handlerOnChangeDesignation = (e) => {
    setDesignation(e.target.value);
  };
  const handlerOnChangePrix = (e) => {
    setPrix(e.target.value);
  };
  const handlerAddArticle = (e) => {
    setArticle(e.target.Article);
  };
  return (
    <div className="container">
      <div className="list">
        <h2 className="title">Ajout d'un Article</h2>
        <div>
          <label>Id:</label>
          <input type="text" onChange={handlerOnChangeId} value={id} />
        </div>
        <div>
          <label>designation:</label>
          <input type="text" onChange={handlerOnChangeDesignation} value={designation}/>{" "}
        </div>{" "}
        <div>
          {" "}
          <label>prix:</label>
          <input type="text" onChange={handlerOnChangePrix} value={prix} />{" "}
        </div>{" "}
        <div>
          {" "}
          <input type="button" value="Ajouter" onClick={handlerAddArticle}/>{" "}
        </div>{" "}
        <div>
          {" "}
          <h3>liste Articles</h3>
          <ul>{Article}</ul>{" "}
        </div>{" "}
      </div>{" "}
    </div>
  );
}

when I click on the button the function "handlerAddArticle" shows the article like that

enter image description here

The problem is that the list doesn't show when the function is being used

const handlerAddArticle = (e) => {
    setArticle(e.target.Article);
  };

CodePudding user response:

Need to add the item to the list

setArticle(prev => [...prev, {id,designation,prix}]);

use map to show items in the dom

 <ul>{Article.map(i => <><li>{i.id} | {i.designation}  | {i.prix} </li></>)}</ul>{" "}

Demo

  • Related