Last active
May 10, 2017 09:18
-
-
Save JamieBradders/efb2f93ab1c0042198fad9d58f42b0b5 to your computer and use it in GitHub Desktop.
Interacting Stateful Components with Stateless Components
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<title>Hello World</title> | |
<script src="https://unpkg.com/react@latest/dist/react.js"></script> | |
<script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script> | |
<script src="https://unpkg.com/[email protected]/babel.min.js"></script> | |
</head> | |
<body> | |
<div id="root"></div> | |
<script type="text/babel"> | |
// Create a stateless component | |
const PeopleManager = (props) => { | |
return ( | |
<div className="people-manager"> | |
<header className="people-manager__header"> | |
<h1>Manage People</h1> | |
</header> | |
<div className="people-manager__controls"> | |
<button onClick={props.handler}>Add Person</button> | |
</div> | |
<div className="people-manager__people"> | |
<ul> | |
{ | |
props.people.map((person, index) => { | |
return <li key={index}>{person}</li> | |
}) | |
} | |
</ul> | |
</div> | |
</div> | |
) | |
} | |
// Create a stateful component | |
class StatefulComponent extends React.Component { | |
constructor(props) { | |
super(props) | |
this.state = { 'people': [] } | |
this.handleClick = this.handleClick.bind(this) | |
} | |
// Simple click method, it will add a name at random to the people array. | |
handleClick(e) { | |
const names = ['Popeye', 'Superman', 'Spiderman', 'Bugs Bunny', 'Hulk'] | |
const name = names[Math.floor(Math.random()*names.length)] | |
this.setState({ | |
'people': this.state.people.concat(name) | |
}) | |
e.preventDefault() | |
} | |
render() { | |
return ( | |
<div> | |
{ PeopleManager({ people: this.state.people, handler: this.handleClick }) } | |
</div> | |
) | |
} | |
} | |
ReactDOM.render( | |
<StatefulComponent />, | |
document.getElementById('root') | |
) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment