Skip to content

Instantly share code, notes, and snippets.

@alundiak
Last active March 8, 2019 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alundiak/11d9ae0c1e6666f0841c3ac1e311a890 to your computer and use it in GitHub Desktop.
Save alundiak/11d9ae0c1e6666f0841c3ac1e311a890 to your computer and use it in GitHub Desktop.
import React from 'react';
class ChildComponent extends React.Component {
render() {
console.log('ChildComponent render');
// const { childData } = this.props;
const { field1, field2 } = this.props;
return (
<div style={{border: '1px dotted red', margin: '20px'}}>
{/* {JSON.stringify(childData)} */}
ChildComponent (data from props): {field1} {field2}
</div>
);
}
}
class ParentComponent extends React.Component {
state = {
parentData: 'data from ParentComponent state.',
childData: null,
counter: 0
};
changeData = (event) => {
const { value } = event.target;
this.setState({
counter: this.state.counter + 1,
// childData: {!this.state.childData}, // also works when passed by reference?
childData: {
field1: 'abc ' + value,
field2: 123 + this.state.counter + 1
}
});
}
render() {
console.log('ParentComponent render');
const { parentData, childData } = this.state;
return (
<div style={{border: '1px dashed green', margin: '20px'}}>
<p>Parent data:</p>
<div>{parentData}</div>
{/* <button onClick={this.changeData}>Click me</button> */}
<label>Select me</label>
<select name="parentSelector" onChange={this.changeData}>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
</select>
<p>Child data:</p>
<div>
{/* <ChildComponent childData={childData} /> */}
<ChildComponent {...childData} />
</div>
</div>
);
}
}
class Test extends React.Component {
render() {
console.log('Test render');
return (
<ParentComponent />
);
}
};
export default Test;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment