Created
October 9, 2019 21:43
-
-
Save aneury1/1a6a594eca6f61186e699558209f768f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React,{Fragment,useContext, useState, createContext} from 'react'; | |
import './App.css'; | |
/* | |
import {myContext, NameProvider } from './Context'; | |
*/ | |
export const myContext = createContext(); | |
export const NameProvider = props=>{ | |
const [person,setPerson] = useState( | |
[ | |
{name:"dfdf", | |
age:0, | |
ocupation:"fdf"} | |
] | |
); | |
return<myContext.Provider value={[person]}> | |
{props.children} | |
</myContext.Provider>; | |
} | |
function Person (){ | |
///const {name} = props; | |
const [person, setPerson]= useContext(myContext); | |
return ( | |
<div> | |
{person.map((p)=> <p>{p.name}</p>)} | |
</div> | |
); | |
} | |
const AddPerson=()=>{ | |
const [name,setName]=useState(''); | |
const [age,setAge]=useState(''); | |
const [ocupation, setOcupation]=useState(''); | |
const [person,setPerson]=useContext(myContext); | |
const updateName= e=>{ | |
setName(e.target.value); | |
} | |
const updateAge= e=>{ | |
setAge(e.target.value); | |
} | |
const updateOcupation = e=>{ | |
setOcupation(e.target.value); | |
} | |
const onSubmit = e =>{ | |
e.preventDefault(); | |
let prevPerson = person; | |
setPerson( prevPerson =>[...prevPerson, {name: name,age: age,ocupation: ocupation}]); | |
} | |
return <div className="form-add-person"> | |
<form onSubmit={onSubmit} > | |
<input type="text" name="name" value={name} onChange={updateName} /> | |
<input type="text" name="age" value={age} onChange={updateAge} /> | |
<input type="text" name="ocupation" value={ocupation} onChange={updateOcupation} /> | |
<input type="submit" name="submit" value="add person" /> | |
</form> | |
</div> | |
} | |
function App() { | |
return ( | |
<div className="App"> | |
<NameProvider> | |
<Fragment> | |
<AddPerson /> | |
<Person /> | |
</Fragment> | |
</NameProvider> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment