DEV Community

message4claver
message4claver

Posted on

Display array from child component in parent component react JavaScript

In the code below, I am passing object from the child component (AddContact.js) to the parent component (App.js) to save in the array in the parent component(contacts). My problem is how to display the array in the parent component. Both log button from the child component and the parent component are logging their array content to the console correctly but its not displaying

App.js


import './App.css';
import AddContact from './contact/AddContact';
import React, {useState} from 'react';

function App() {
    const [contacts, AddContacts] = useState([]);
    const Add = (data)=> {
      contacts.push(data);
    }
  return (
    <div>
        <AddContact Add={Add}/>
        <button onClick={()=>console.log(contacts)}>Parent Contacts Log</button>
        <table>
        {
            contacts.forEach(contact=>{
                <tr><td>contacts.indexOf(contact)</td><td>contact.name</td><td>contact.email</td></tr>
            })
        }
        </table>
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

AddContact.js

import React,{useState} from 'react';

function AddContact(props) {
    const [cont, AddCont] = useState({name:' ',email:' '});
    return (
        <div>
            <div><input type='text' placeholder='Please enter your name' onChange={e=>AddCont({...cont,name:e.target.value})} /></div>
            <div><input type='text' placeholder='Please enter your email'  onChange={e=>AddCont({...cont,email:e.target.value})} /></div>
            <button onClick={()=>props.Add(cont)}>Add Contact</button>
            <div><button onClick={()=>console.log(cont)}>Child Cont Log</button></div>
        </div>
    )
}
export default AddContact;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)