Passing redux action to another component through TabNavigator - reactjs

I have just finish following this tutorial https://www.youtube.com/watch?v=3msLwu25SQY&list=PLk083BmAphjtGWyZUuo1BiCS_ZAgps6j5
Now I want to implement the TabNavigator which look like this
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { ActionCreators } from '../actions'
import { TabNavigator } from 'react-navigation'
import Home from './Home'
const Tabs = TabNavigator({
Home: {
screen: Home,
}
})
class AppContainer extends Component {
render(){
return <Tabs {...this.props}/>
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators(ActionCreators, dispatch)
}
export default connect((state) => { return {} }, mapDispatchToProps)(AppContainer)
However the redux action does not pass to the Home component and I got an error saying this.props.[actionname] is not a function.

show you my project
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<Navigator
initialRoute={{component: AppTabs}}
renderScene={(route, navigator) =>
<route.component {...route.args} navigator={navigator} />
}
/>
</Provider>
)
}
}
change the AppTabs to your Tabs, it maybe works.

Related

What's wrong in the below react redux code snippets?

I have created react app and try to run after adding simple redux stuffs as below.
Initial state value and updated state value(after button click) not appearing in the screen.
No error thrown in the console.
Expected result should be display the initial Message from store as "Please subscribe".
After clicking subscribe button, the text should be change into "Thanks for Subscribing!".
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { createStore } from 'redux';
import reducer from './Reducer';
import { Provider } from 'react-redux';
const store = createStore(reducer);
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
Reducer.js
const initialState = {
message: "Please subscribe!"
};
const reducer = (state = initialState, action) => {
console.log(action);
const newState = { ...state };
if (action.type === "PRINT_ITEM") {
newState.message = "Thanks for subscribing!"
};
return newState;
}
export default reducer;
App.js
import { Component } from 'react';
import './App.css';
import { NewComp } from './NewComp';
class App extends Component {
render() {
return (
<div className="App">
<h1>Welcome</h1>
<NewComp />
</div>
);
}
}
export default App;
NewComp.js
import React, { Component } from 'react'
import { connect } from 'react-redux';
export class NewComp extends Component {
styles = {
fontStyle: 'italic',
color: 'purple'
}
render() {
return (
<div className="App">
<h3 style={this.styles}>{this.props.msg}</h3>
<button onClick={this.props.ButtonChange}>Subscribe</button>
</div>
);
}
}
const mapStateToProps = (state) => {
console.log(state); //Not get fired
return {
msg: state.message
};
};
const mapDispatchToProps = (dispatch) => {
console.log(dispatch); //Not get fired
return {
ButtonChange: () => dispatch({ type: "PRINT_ITEM" })
};
};
export default connect(mapStateToProps, mapDispatchToProps)(NewComp);
In App.js, you're importing the named export from NewComp, which is not the Redux-connected version. Instead, import the default export, which is Redux-connected:
import NewComp from './NewComp';

React prop being marked as undefined

So I have been working on a nodejs website until I ran until a really stupid error which had me stopped for a solid hour. All of my other redux actions work except for the logout which gives me this error.
Failed prop type: The prop logout is marked as required in Logout, but its value is undefined.
Here is the code for the logout component
import React, { Component, Fragment } from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { logout } from "../../actions/authActions";
import PropTypes from "prop-types";
export class Logout extends Component {
static propTypes = {
logout: PropTypes.func.isRequired
};
render() {
return (
<div>
<Link onClick={this.props.logout} to="#">
Logout
</Link>
</div>
);
}
}
export default connect(null, { logout })(Logout);
Here is the action code
export const logout = () => {
return {
type: LOGOUT_SUCCESS
};
};
The value is clearly defined. Please let me know what here is not working
Found the issue,
If my redux understanding is correct, I cannot export the class and connect as well. So I had to remove the class export and change it to this
import React, { Component } from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { logout } from "../../actions/authActions";
import PropTypes from "prop-types";
class Logout extends Component {
static propTypes = {
logout: PropTypes.func.isRequired
};
render() {
return (
<div>
<Link onClick={this.props.logout} to="#">
Logout
</Link>
</div>
);
}
}
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
// error: state.error
});
export default connect(mapStateToProps, { logout })(Logout);

React export React.createContext not defined

I am trying to learn React Context and got stuck. Need help.
App.js
import React from 'react';
import Header from './components/Header';
export const MyContext = React.createContext("Default");
class App extends React.Component {
render() {
return (
<MyContext.Provider value="dark">
<Header />
</MyContext.Provider>
);
}
}
export default App;
Header/index.js
import React, { Component } from 'react'
import { MyContext } from "./../../App";
class Header extends Component {
//static contextType = MyContext;
render() {
return (
<div>
{this.context}
</div>
)
}
}
Header.contextType = MyContext;
export default Header;
Got an error MyContext is not defined.
It works when i move Header class to App.js
What am i doing wrong? Tnx for your help
There are two ways to use context either use:
1. By using context consumer :
<MyContext.Consumer>
{
contextValue => {
return <div>
{value}
</div>
}
}
<MyContext.Consumer>
2. By assigning context to a object:
static contextType = MyContext;
render(){
const {value1,value2.......} = this.context
}
For more information about Context visit the React official page.
https://reactjs.org/docs/context.html
The provider only holds the the value for you(a bit like a store). It is the consumer that makes it available to your components.
Headerjs should look like this
// Header.js
import React, { Component } from 'react'
import { MyContext } from "./../../App";
class Header extends Component {
//static contextType = MyContext;
render() {
return (
<MyContext.Consumer>
{ value => {
return <div>
{value}
</div>
}}
<MyContext.Consumer>
)
}
}
// Header.contextType = MyContext; not needed for react v16+
export default Header;
To get more power out of Context i will suggest combining with Higher Order Components. for example if what you want is a theming system
you can do this.
import React from "react";
const themes = {
dark: {
background: "#333"
},
light: {
background: "#f5f5f9"
}
};
const { Provider, Consumer } = React.createContext(themes);
export const ThemeProvider = ({ children }) => {
return <Provider value={themes}>{children}</Provider>
};
export const withTheme = theme => {
return Component => props => <Consumer>
{themes => {
return <Component {...props} style={{ ...themes[theme]}} />;
}}
</Consumer>
};
in app.js
import Header from "./Header";
import { ThemeProvider } from './Theme'
class App extends React.Component {
render() {
return (
<ThemeProvider>
<Header />
</ThemeProvider>
);
}
}
and lastly Header.js
import React, { Component } from "react";
import { withTheme } from "./Theme";
class Header extends Component {
//static contextType = MyContext;
render() {
return <h1 style={{ ...this.props.style }}>Header</h1>;
}
}
export default withTheme("dark")(Header);
You can read MY article on using context for auth for more

Programatically going back to home page with React

I've read the articles on here on how to do this and have chosen the withRouter(({ history }) => history.push("/")); method, but my code below isn't working.. What am I doing wrong?
import React from "react";
import SearchBox from "./SearchBox";
import { withRouter } from "react-router-dom";
class SearchParams extends React.Component {
handleSearchSubmit() {
withRouter(({ history }) => history.push("/"));
}
render() {
return (
<div className="search-route">
<SearchBox search={this.handleSearchSubmit} />
</div>
);
}
}
export default SearchParams;
withRouter is a higher order component which takes a component as first argument and will make it so that component gets the history added to its regular props.
You can instead use it on the component when you export it, and access the history from this.props.history.
class SearchParams extends React.Component {
handleSearchSubmit = () => {
this.props.history.push("/");
};
render() {
return (
<div className="search-route">
<SearchBox search={this.handleSearchSubmit} />
</div>
);
}
}
export default withRouter(SearchParams);

New to react and Redux, why am i getting an undefined store being passed?

I am not sure if I am even setting up this redux-react project correctly. I am confused as to how I can actually start using store within my react app.
When I try to console.log store I am getting undefined. I have gotten most of this from a boilerplate and am unsure of how some of these parts interact. Currently I have an index.js with
import { Provider } from 'react-redux'
import { configureStore } from './store/configureStore';
const store = configureStore()
import { Root} from './containers/Root';
import Home from './containers/Home'
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={Root}>
<IndexRoute component={Home} />
</Route>
</Router>
</Provider>,
document.getElementById('root')
);
Root.js :
import React, { Component } from 'react';
import DevTools from './DevTools';
import MyNavbar from '../components/MyNavbar';
import Footer from '../components/Footer'
module.exports = class Root extends Component {
render() {
const { store } = this.props;
console.log(store)
return (
<div>
<MyNavbar />
{this.props.children}
<Footer />
{/* Being the dev version of our Root component, we include DevTools below */}
{/*<DevTools />*/}
</div>
);
}
};
Home component:
import React, { Component, PropTypes } from 'react';
import { Row, Col, Grid } from 'react-bootstrap'
import HowItWorks from '../components/HowItWorks'
import GetStarted from '../components/GetStarted'
import Setup from './Setup'
export default class Home extends Component {
render() {
// we can use ES6's object destructuring to effectively 'unpack' our props
return (
<section>
<div className="slider-wrapper">
<GetStarted />
</div>
<Grid>
<div className="howwork-wrapper">
<Row >
<Col md={12}>
<HowItWorks />
</Col>
</Row>
</div>
</Grid>
</section>
);
}
}
configureStore.js :
import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from '../reducers';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
import DevTools from '../containers/DevTools';
const logger = createLogger();
const finalCreateStore = compose(
applyMiddleware(logger, thunk),
DevTools.instrument()
)(createStore);
module.exports = function configureStore(initialState) {
const store = finalCreateStore(rootReducer, initialState);
if (module.hot) {
module.hot.accept('../reducers', () =>
store.replaceReducer(require('../reducers'))
);
}
return store;
};
reducers/index.js:
import { combineReducers } from 'redux';
import auth from './auth'
const rootReducer = combineReducers({
auth
});
export default rootReducer;
reducers/auth.js:
import { LOGIN, LOGIN_FAIL, LOGOUT } from '../constants/ActionTypes'
export default function auth(state = {}, action) {
switch (action.type) {
case LOGIN:
return state;
case LOGIN_FAIL:
return state ;
case LOGOUT:
return state ;
default:
return state;
}
}
constants/ActionTypes:
export const LOGIN = 'LOGIN';
export const LOGIN_FAIL = 'LOGIN_FAIL';
export const LOGOUT = 'LOGOUT';
You need to connect your components to get access to the store/state. To do this, modify your Root component like this:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import DevTools from './DevTools';
import MyNavbar from '../components/MyNavbar';
import Footer from '../components/Footer'
class Root extends Component {
render() {
const { state } = this.props;
console.log(state)
return (
<div>
<MyNavbar />
{this.props.children}
<Footer />
{/* Being the dev version of our Root component, we include DevTools below */}
{/*<DevTools />*/}
</div>
);
}
};
const mapStateToProps = (state) => {
return {
state: state
}
}
module.exports = connect(mapStateToProps)(Root);
A few notes, since you are transpiling anyway, you could export instead of module.exports in your declaration. Also, generally you do not want to expose your entire state to a single component. You can connect multiple components (make them "containers") by following this pattern.
The following is an example component connected to your state.
import React, { Component } from 'react';
import { connect } from 'react-redux';
export class SomeComponent extends Component {
render() {
const { someKey, dispatchSomething } = this.props;
return (
<div onClick={dispatchSomething}>
<h1>My rendered someKey variable: {someKey}</h1>
</div>
);
}
};
const mapStateToProps = (state) => {
return {
someKey: state.someReducer.someKey
}
}
const mapDispatchToProps = (dispatch) => {
return {
dispatchSomething: () => dispatch(someActionCreator())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SomeComponent);
References
react-redux API: connect

Resources