Skip to content

Instantly share code, notes, and snippets.

@JamieBradders
Last active May 10, 2017 09:18
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 JamieBradders/efb2f93ab1c0042198fad9d58f42b0b5 to your computer and use it in GitHub Desktop.
Save JamieBradders/efb2f93ab1c0042198fad9d58f42b0b5 to your computer and use it in GitHub Desktop.
Interacting Stateful Components with Stateless Components
<!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/babel-standalone@6.15.0/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