Skip to content

Instantly share code, notes, and snippets.

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 rabajaj0509/98a4eb77545b9a48af76997cc0b8f8aa to your computer and use it in GitHub Desktop.
Save rabajaj0509/98a4eb77545b9a48af76997cc0b8f8aa to your computer and use it in GitHub Desktop.
import React from "react";
export class Child extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
const name = e.target.value;
this.props.onChange(name);
}
render() {
return (
<div>
<h1>Hey my name is {this.props.name}!</h1>
<select id="great-names" onChange={this.handleChange}>
<option value="Frarthur">Rahul</option>
<option value="Gromulus">Anuj</option>
<option value="Thinkpiece">Ron</option>
</select>
</div>
);
}
}
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import Parent from "./Parent";
import * as serviceWorker from "./serviceWorker";
ReactDOM.render(
<React.StrictMode>
<Parent />
</React.StrictMode>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
The parent component `binds` the newly-defined method to the current instance of the component in its constructor.
This ensures that when we pass the method to the child component, it will still update the parent component.
Once the parent has defined a method that updates its state and bound to it, the parent then passes that method down to a child.
The child receives the passed-down function, and uses it as an `event handler`.
import React from "react";
import ReactDOM from "react-dom";
import { Child } from "./Child";
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { name: "Rahul" };
this.changeName = this.changeName.bind(this);
}
changeName(newName) {
this.setState({
name: newName
});
}
render() {
return (
<div>
{this.state.name}
<Child name={this.state.name} onChange={this.changeName} />
</div>
);
}
}
export default Parent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment