Skip to content

Instantly share code, notes, and snippets.

@muhammadawaisshaikh
Created March 10, 2020 10:42
Show Gist options
  • Save muhammadawaisshaikh/715e9fe5df7c8f5547332628d7cc16a8 to your computer and use it in GitHub Desktop.
Save muhammadawaisshaikh/715e9fe5df7c8f5547332628d7cc16a8 to your computer and use it in GitHub Desktop.
How to share and change state between components using props
// 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;
// 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