React and immutable example of a simple top down, one way data flow, single state app.
A Pen by Brian Emil Hartz on CodePen.
| <div id="mainApp"></div> |
React and immutable example of a simple top down, one way data flow, single state app.
A Pen by Brian Emil Hartz on CodePen.
| class MainApp extends React.Component { | |
| constructor(){ | |
| super(); | |
| this.state = { | |
| data: Immutable.Map({ | |
| list: Immutable.List(['Item1']) | |
| }) | |
| } | |
| this._updateList = this._updateList.bind(this); | |
| } | |
| _updateList(newValue){ | |
| this.setState(previousState=>{ | |
| let list = this.state.data.get('list'); | |
| return {data: previousState.data.set('list', list.push(newValue))} | |
| } | |
| ) | |
| } | |
| render(){ | |
| let {list} = this.state.data.toJS(); | |
| return (<div className="appContainer"> | |
| <h3>mainApp</h3> | |
| <div className="flexContainer"> | |
| <DisplayData list={list}/> | |
| <InputData onNewItem={this._updateList} nextItem={list.length + 1}/> | |
| </div> | |
| </div>) | |
| } | |
| } | |
| class DisplayData extends React.Component { | |
| render(){ | |
| let $renderedFoos = this.props.list.map(item=>(<div>{item}</div>)); | |
| return( | |
| <div className="displayData"> | |
| <h4>DisplayData Component</h4> | |
| {$renderedFoos} | |
| </div> | |
| ) | |
| } | |
| } | |
| class InputData extends React.Component { | |
| render(){ | |
| let nextItemText = 'Item' + this.props.nextItem; | |
| return( | |
| <div className="inputData"> | |
| <h4>InputData Component</h4> | |
| <button className="addItem" onClick={()=>this.props.onNewItem(nextItemText)}>Add Item +</button> | |
| </div> | |
| ) | |
| } | |
| } | |
| React.render(<MainApp/>, document.getElementById("mainApp")); |
| <script src="//cdnjs.cloudflare.com/ajax/libs/react/0.13.0/react.min.js"></script> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.4/immutable.min.js"></script> |
| .appContainer { | |
| padding: 5px; | |
| border: solid 4px #eeeeee; | |
| width: 50%; | |
| margin: 0 auto; | |
| text-align: center; | |
| } | |
| .flexContainer { | |
| display: flex; | |
| justify-content: space-around; | |
| } | |
| .displayData { | |
| background-color: lightgray; | |
| padding: 5px 5px 15px 5px; | |
| border-bottom: solid 4px darkgray; | |
| border-right: solid 4px darkgray; | |
| width: 45% | |
| } | |
| .inputData { | |
| background-color: lightblue; | |
| padding: 5px 5px 15px 5px; | |
| border-bottom: solid 4px darkblue; | |
| border-right: solid 4px darkblue; | |
| width: 45% | |
| } | |
| .addItem { | |
| border: none; | |
| border-bottom: solid 2px darkgray; | |
| border-right: solid 2px darkgray; | |
| background-color: white; | |
| cursor: pointer; | |
| &:hover { | |
| border: none; | |
| border-top: solid 2px darkgray; | |
| border-left: solid 2px darkgray; | |
| background-color: lightgray; | |
| } | |
| &:focus { | |
| outline:0; | |
| } | |
| } |