Created
March 10, 2020 10:42
-
-
Save muhammadawaisshaikh/715e9fe5df7c8f5547332628d7cc16a8 to your computer and use it in GitHub Desktop.
How to share and change state between components using props
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
// Child | |
import React, { useState, Component } from 'react'; | |
import Input from '../../shared/input-box/InputBox' | |
const Form = function (props) { | |
const {toggle, toggler} = props; | |
const [value, setValue] = useState(''); | |
const onchange = (data) => { | |
setValue(data) | |
console.log("Form>", data); | |
} | |
const togller = () => { | |
toggler(); | |
} | |
console.log(toggle); | |
return ( | |
<div> | |
<Input data={value} onchange={(e) => { onchange(e) }}/> | |
<a onClick={togller}>state: {toggle}</a> | |
</div> | |
); | |
} | |
export default Form; |
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
// Parent | |
import React, { Component } from 'react'; | |
import Form from './form/Form' | |
export default class Main extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
name: 'React Test App', | |
toggle: true | |
}; | |
} | |
handleToggler = () => { | |
if(this.state.toggle) this.setState({toggle: false}) | |
if(!this.state.toggle) this.setState({toggle: true}) | |
console.log(this.state.toggle); | |
} | |
render() { | |
return ( | |
<div> | |
<h2>{this.state.name}</h2> | |
<Form toggle={this.state.toggle} toggler={this.handleToggler} /> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment