Skip to content

Instantly share code, notes, and snippets.

@danibrear
Created August 12, 2016 13:13
Show Gist options
  • Save danibrear/5208b5ec1268c4c8ba8265d1bb6f0496 to your computer and use it in GitHub Desktop.
Save danibrear/5208b5ec1268c4c8ba8265d1bb6f0496 to your computer and use it in GitHub Desktop.
React Redux with Child Context
import React, { Component, PropTypes } from 'react';
import logo from './logo.svg';
import './App.css';
import { connect } from 'react-redux';
const mapStateToProps = (state) => ({
name: state.name,
});
class ChildApp extends Component {
render() {
return (<div>Context age is: {this.context.age}</div>);
}
}
ChildApp.contextTypes = {
age: PropTypes.number,
};
const ConnectedChildApp = connect(mapStateToProps)(ChildApp);
class App extends Component {
getChildContext() {
return {
age: 31,
};
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<div>
{`State name is: ${this.props.name}`}
</div>
<ConnectedChildApp />
</div>
);
}
}
App.childContextTypes = {
age: PropTypes.number,
};
export default connect(mapStateToProps)(App);
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { Provider } from 'react-redux';
import { createStore, combineReducers } from 'redux';
const name = (state = 'David Brear', action) => {
switch (action.type) {
case 'UPDATE_NAME_SUCCESS':
return action.payload;
default:
return state;
}
};
const reducer = combineReducers({
name,
});
const store = createStore(reducer);
const Root = () => (<Provider store={store}>
<App />
</Provider>);
ReactDOM.render(
<Root />,
document.getElementById('root')
);
{
"name": "react-redux-child-context",
"version": "0.0.1",
"private": true,
"devDependencies": {
"react-scripts": "0.2.1"
},
"dependencies": {
"react": "^15.2.1",
"react-dom": "^15.2.1",
"react-redux": "^4.4.5",
"redux": "^3.5.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "./node_modules/react-scripts/config/eslint.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment