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:-
- combine them in a new array but it didn’t work well
- 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
For your map method you should use an array of objects, like this:
Each Object will be like this:
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
If you want to use an
Object
to render withmap()
as anArray
, we have some solution as:Object.values(yourObject)
-> this will return an array of values of your objectObject.entries(yourObject)
-> this will return an array of keys, values of your objectthen you can use
map()
You can refer this, hope it match your problem: https://stackblitz.com/edit/stackblitz-starters-pmo76x?file=src%2FApp.tsx