skip to Main Content

I am trying to render a component only once by passing it two arrays and I want it to take the first element of the first array and the first element of the second array and render once and so on. i am trying to use the map() method since they are arrays heres what i have tried:-

  1. combine them in a new array but it didn’t work well
  2. comnine them in a new object and i could not find an equivalent for the map() method
function AddNotes() {
  const [noteDraft, setNoteDraft] = useState('');
  const [notes, setNotes] = useState([]);
  const [titleDraft, setTitleDraft] = useState('');
  const [titles, setTitles] = useState([]);

  const wholeNote = [notes, titles];

  function handleSubmit(e) {
    e.preventDefault();
    if (!noteDraft && !titleDraft) return;
    onAddItems(noteDraft, titleDraft);
    setNoteDraft('');
    setTitleDraft('');
  }

  function onAddItems(note, title) {
    setNotes(notes => [...notes, note]);
    setTitles(titles => [...titles, title]);
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="enter your title..."
          value={titleDraft}
          onChange={e => setTitleDraft(e.target.value)}
        />
        <>
          <textarea
            type="text"
            placeholder="type your note..."
            rows="7"
            cols="60"
            wrap="hard"
            value={noteDraft}
            onChange={e => setNoteDraft(e.target.value)}
          ></textarea>
          <button>Add note</button>
        </>
      </form>
      <div>
        {wholeNote.map(note => (
          <SingleNote note={[...note[0]]} title={[...note[1]]} key={notes} />
        ))}
      </div>
    </div>
  );
}

the two arrays are supposed to show the title of a note and its body (description)

2

Answers


  1. For your map method you should use an array of objects, like this:

    let noteList = [Object1, Object2, ...] 
    

    Each Object will be like this:

    noteOne = {title: "abc", desc: "xyz", ...}
    

    If you want access to title’s property, then use: noteOne.title. The same for description.
    If you want access to title of noteOne from noteList, then use: noteList[0].title

    Login or Signup to reply.
  2. If you want to use an Object to render with map() as an Array, we have some solution as:

    1. Object.values(yourObject) -> this will return an array of values of your object

    2. Object.entries(yourObject)-> this will return an array of keys, values of your object

    then you can use map()

    You can refer this, hope it match your problem: https://stackblitz.com/edit/stackblitz-starters-pmo76x?file=src%2FApp.tsx

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search