In the js file below we create an integer(ttSelectedItem).
How do you use it on another .js file ?
(Without clicking any button)
Is AsyncStorage solving that problem? If it is true, how?
import React, { Component } from 'react';
import {Platform,StyleSheet,Text,View,Image,ImageBackground} from 'react-native';
import Picker from 'react-native-wheel-picker'
var PickerItem = Picker.Item;
var numberList = [];
var ttSelectedItem,
for (let i = 0; i < 41; i++){
numberList.push(i.toString());
}
export default class yks extends Component<{}> {
constructor(props) {
super(props);
this.state = {
ttSelectedItem : 20,
itemList: numberList,
};
}
onPickerSelect (index, selectedItem) {
this.setState({
[selectedItem] : index,
})
}
render () {
return (
<View>
<Picker style={{width: "100%", height: "100%"}}
selectedValue={this.state.ttSelectedItem}
onValueChange={(index) => this.onPickerSelect(index, 'ttSelectedItem')}>
{this.state.itemList.map((value, i) => (
<PickerItem label={value} value={i} key={"money"+value}/>
))}
</Picker>
</View>
);
}
}
You can create a file ttSelectedItem.js and import it in all the components you need.
Example:
//ttSelectedItem.js
const ttSelectedItem = 'Hello';
export default ttSelectedItem
//YourComponent.js
import ttSelectedItem from './path-to-ttSelectedItem';
class YourComponent extends React.Component {
console.log(ttSelectedItem); // print Hello
}
More info: https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
You can also pass down the prop from a parent component to its children.
Example:
// App.js
import FirstComponent from 'path-to-first-component';
import SecondComponent from 'path-to-second-component';
class App extends React.Component {
render() {
return (
<View>
<FirstComponent ttSelectedItem={'Hello'} />
<SecondComponent ttSelectedItem={'Hello'} />
</View>
)
}
}
// FirstComponent.js
class FirstComponent extends React.Component {
console.log(this.props.ttSelectedItem) //print Hello
}
export default FirstComponent
// SecondComponent.js
const SecondComponent = (props) => {
console.log(props.ttSelectedItem) //print Hello
}
export default SecondComponent
Depending on how complex your code will be, you can use HOCs to wire up some data and pass down your components
Example:
//ttSelectedItem.js
const ttSelectedItem = (Component) => {
return <Component ttSelectedItem={'Hello'} />
}
export default ttSelectedItem;
//YourComponent.js
import ttSelectedItem from 'path-to-ttSelectedItem';
class YourComponent extends Component{
(...)
console.log(this.props.ttSelectedItem); //print Hello
(...)
}
export default ttSelectedItem(YourComponent);
More detail: https://reactjs.org/docs/higher-order-components.html
Or if you need an even complex code, you can use Redux Store to keep this data
Example using Redux and ReduxThunk:
//App.js
import ReduxThunk from 'redux-thunk';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reducer from 'path-to-your-reducer';
import YourComponent from 'path-to-your-component';
class App extends Component {
render() {
const store = createStore(reducer, {}, applyMiddleware(ReduxThunk));
return (
<Provider store={store}>
<YourComponent />
</Provider>
);
}
}
// YourComponent.js
import { connect } from 'react-redux';
class YourComponent extends React.Component {
console.log(this.props.ttSelectedItem) // prints Hello
}
const mapStateToProps = function(state){
return {
ttSelectedItem: state.ttSelectedItem,
}
}
export default connect(mapStateToProps, {})(MainAppContainer)
// Reducer.js
const INITIAL_STATE = {
ttSelectedItem: 'Hello',
};
export default (state = INITIAL_STATE) => {
return state;
};
More info: https://redux.js.org/basics/store
The last example is just to show another way to handle data between components using Redux. It should be used only when dealing with really complex data sharing.
I'd suggest you to just follow the first example, it might be enough
Hope it helps
Related
I am trying to get adaptValue from Component1 and use it in Component2. For some reason this does not work since my adaptValue is always null/undefined. Is it because Parent is a functional component?
const Parent = (props) => {
const [adaptValue, setAdapt] = useState(null);
return (
<div>
<Component1 setAdapt={setAdapt}/>
<Component2 adaptValue={adaptValue}/>
</div>
)
}
export default class Component1 extends Component {
constructor(props) {
super(props);
}
adaptValue = (value) =>{
DO_SOMETHING_WITH_VALUE
}
componentDidMount() {
this.props.setAdapt(this.adaptValue);
}
render() {
return something;
}
}
export default class Component2 extends Component {
constructor(props) {
super(props);
}
someFunction = (value) =>{
...
//adaptValue is always undefined
this.props.adaptValue(value)
...
}
render() {
return something;
}
}
UPDATE Made the parent a class component in the end and all works. Wondering whether this is a compatibility issue between functional or class-based components.
When passing setAdapt to Component1 ... setAdapt is already a function. There is no need to wrap it in another one. Component1 will modify the value, and Component2 will display it. Function Components have nothing to do with the behavior.
Try ...
App.js
import React, { useState } from "react";
import "./styles.css";
import Component1 from "./Component1";
import Component2 from "./Component2";
export default function App() {
const [adaptValue, setAdapt] = useState(null);
return (
<div>
<Component1 setAdapt={setAdapt} />
<Component2 adaptValue={adaptValue} />
</div>
);
}
Component1.js
import React, { Component } from "react";
export default class Component1 extends Component {
handleClick = () => {
this.props.setAdapt("New Value");
};
render() {
return <button onClick={() => this.handleClick()}>Set Value</button>;
}
}
Component2.js
import React, { Component } from "react";
export default class Component2 extends Component {
render() {
return !!this.props.adaptValue ? (
<h1>{`"${this.props.adaptValue}" <- Value of adaptValue`}</h1>
) : (
<h1>adaptValue Not Assigned</h1>
);
}
}
Sandbox Example ...
I am getting an error "MobX injector: Store 'systemStore' is not available! make sure it is provided by some provider. What I really need to do is pass the store to all of my components so that I hace access to them in the this.props.systemStore in like, componentWillMount
import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { AppLoading, Asset, Font } from 'expo';
import { Ionicons } from '#expo/vector-icons';
import {NavigationActions} from 'react-navigation'
import RootNavigation from './navigation/RootNavigation';
import { inject, observer, Provider } from 'mobx-react';
import { observable, action } from "mobx";
import SystemStore from "./stores/SystemStore";
class Main extends React.Component {
render() {
return (
<Provider systemStore={SystemStore} >
<App />
</Provider>
);
}
}
#inject("systemStore")
export default class App extends React.Component {
state = {
isLoadingComplete: false,
};
render() {
if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {
return (
<AppLoading
startAsync={this._loadResourcesAsync}
onError={this._handleLoadingError}
onFinish={this._handleFinishLoading}
/>
);
} else {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
{Platform.OS === 'android' &&
<View style={styles.statusBarUnderlay} />}
<RootNavigation />
</View>
);
}
}
_loadResourcesAsync = async () => {
return Promise.all([
Font.loadAsync([
// This is the font that we are using for our tab bar
Ionicons.font,
// We include SpaceMono because we use it in HomeScreen.js. Feel free
// to remove this if you are not using it in your app
{ 'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf') },
]),
Asset.loadAsync([
require('./assets/images/robot-dev.png'),
require('./assets/images/robot-prod.png'),
]),
]);
};
_handleLoadingError = error => {
console.warn(error);
};
_handleFinishLoading = () => {
this.setState({ isLoadingComplete: true });
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
statusBarUnderlay: {
height: 24,
backgroundColor: 'rgba(0,0,0,0.2)',
},
});
Expo.registerRootComponent(Main);
and the store looks like this
import {observable, action, computed} from 'mobx'
class SystemStore {
#observable loggedIn = false;
#observable controlAuth = false;
#observable testingKey = "Testing-Yo"
}
export default new SystemStore()
i have been all over looking for a solution, just cannot seem to get my head around this one. thanks
So how I deal with this issue is, I create a file called stores.js which looks like this:
import SystemStore from './stores/systemStore';
const systemStore = new SystemStore();
export {
SystemStore
}
export default {
systemStore
}
In this file I import and export all my stores, so that I can always call stores.systemStore (and all other stores you have) with just importing my stores.js like this
import React from 'react';
import {observer} from 'mobx-react';
import stores from './../../stores';
#observer
class TestComponent extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div>
{stores.systemStore.testingKey}
</div>
);
}
}
export default TestComponent;
And my stores look like this then:
import store from 'store';
import {observable, action, computed} from 'mobx';
class systemStore {
#observable loggedIn = false;
#observable controlAuth = false;
#observable testingKey = "Testing-Yo";
}
export default systemStore;
I hope this will help you. It works for me :)
I am just beginning to play with react/redux. I just want to input some text and hit submit and then pass that to another component that will display whatever was input.
I know I can get the data from point A to B because if I use store.subscribe than I can access the state and it is always accurate. I am trying to use mapStateToProps though and I am not having any luck.
I am not using mapDispatchToProps so maybe that is an issue? I cant seem to find a good simple example. mapStateToProps also only seems to run when I refresh the page (using webpack-dev-server) since it only logs one time on page load and never again.
_______________ Input.js _________________
import React from 'react';
import store from '../redux/store';
import { connect } from 'react-redux';
import { addSearchParam } from '../redux/actions';
export default class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
player: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
player: event.target.value
});
}
handleSubmit(event) {
event.preventDefault();
store.dispatch(addSearchParam(this.state.player))
}
render() {
return ( <form onSubmit = {this.handleSubmit} >
<label>
<input type="text" value={this.state.player}
onChange={this.handleChange}/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
_______________ Info.js _________________
import React from 'react';
import store from '../redux/store';
import { connect } from 'react-redux';
class Info extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h2> {this.props.player}</h2>
)
}
}
function mapStateToProps(state) {
console.log("mapStateToPropsInfo: ", state)
return {
player: state.player
}
}
export default connect(mapStateToProps, null)(Info);
_______________ reducers.js _________________
'use strict';
import {
combineReducers
} from 'redux';
const SEARCH_PARAM = 'SEARCH_PARAM';
const searchReducer = (state = '', action) => {
if (action.type === SEARCH_PARAM) {
return action.text;
}
return state;
}
export const reducers = combineReducers({
searchReducer
})
export default reducers;
_______________ actions.js _________________
'use-strict';
export const addSearchParam = input => {
return {
type: 'SEARCH_PARAM',
id: 'player',
text: input
}
}
_______________ index.js _________________
'use-strict';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './js/App';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from './js/redux/reducers'
let store = createStore(reducers)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root')
);
Those seem to be the most important files related to this problem but I can provide more if necessary. Thanks for any help. Hopefully im just missing something simple.
I think the issue is that you have written actions but never used/connected it. You need to use mapDispatchToProps in Input.js.
First import the action in input.js like this:
import { addSearchParam } from './actions';
Write mapDispatchToProps function like this:
function mapDispatchToProps(dispatch){
return bindActionCreators({addSearchParam}, dispatch);
}
Then, inside Input.js in handleSubmit function do this:
this.props.addSearchParam(this.state.player)
Also, instead of exporting class while declearing, change export statement of Input.js to also bind the mapDispatchToProps :
export default connect(null, mapDispatchToProps)(Input);
I´m pretty new to React and Redux and have some issue during my first steps with it. I tried to follow the examples in the Redux Doc´s, but it´s hard for me to understand everything, because every example is jumping between ES5 - 6 or even 7 syntax.
However, When I try to dispatch an action I got the following error
Uncaught TypeError: (0 , _index2.default) is not a function
Error Message
I know that SO Community doesn´t prefer so much code within one Question, but I don´t know where the problem is coming from. Sorry for that!
These is my Code:
Index.js
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './containers/App'
import configureStore from './store/configureStore'
const store = configureStore()
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
My Store
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import index from '../reducers'
export default function configureStore(preloadedState) {
const store = createStore(
index,
preloadedState,
applyMiddleware(thunkMiddleware, createLogger())
)
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers').default
store.replaceReducer(nextRootReducer)
})
}
return store
}
My Container Component
import React, { Component, PropTypes } from 'react'
import AddTodo from '../components/AddTodo'
import { connect } from 'react-redux'
import addItem from '../actions/index'
class App extends Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
}
handleClick(e){
console.log("click")
console.log(e);
const {dispatch} = this.props
dispatch(addItem(e));
}
render() {
return (
<div>
< h1 > Hallo </h1>
<AddTodo handleAddItem={this.handleClick}/>
</div>
)
}
}
App.propTypes = {
dispatch: PropTypes.func.isRequired
}
function mapStateToProps(state){
return {
AddTodo
}
}
export default connect (mapStateToProps)(App)
My Child Component:
import React, { Component, PropTypes } from 'react'
import addItem from '../actions/index'
export default class AddTodo extends Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
this.state = {newItem: ''}
}
onChange(e){
console.log("change")
console.log(e.target.value);
this.setState({newItem: e.target.value})
}
handleClick(e){
this.props.handleAddItem(this.state.newItem)
// const {dispatch} = this.props
// console.log("clickc")
// console.log(this.state.newItem);
// dispatch(addItem(this.state.newItem))
}
render() {
return (
<div>
<h3>Add Item </h3>
<input
type="text"
value={this.state.newItem}
onChange={this.onChange.bind(this)}
/>
<button onClick={this.handleClick}>Hallo</button>
</div>
)
}
}
The Reducer
export default (state = [], action) => {
switch (action.type){
case 'ADD_ITEM':
return action.item
}
}
And Finally the action
export function addItem(item){
console.log("addTOdo")
return {
type: 'ADD_ITEM',
item
}
}
I hope someone can help me here, sitting since several hours and don´t understand what is happening.
You are not exporting action creator as default. You need either
export default function addItem(item){
console.log("addTOdo")
return {
type: 'ADD_ITEM',
item
}
}
or
import {addItem} from '../actions/index'
I'm new to redux and having trouble wrapping my head around presentational and container components.
Relevant stack:
react v0.14.8
react-native v0.24.1
redux v3.5.2
react-redux v4.4.5
The issue:
I have a login button component, which when rendered checks the login status and calls the onSuccessfulLogin action which updates the state with the user's Facebook credentials.
However, when trying to separate this into separate presentational/container components, I'm unable to call the onSuccessfulLogin action: Error: onSuccessfulLogin is not defined.
What am I doing wrong here? I'd imagine there's something simple that I'm not understanding with the relationship between the two components and the connect() function.
Presentational Component (Login.js)
import React, { PropTypes } from "react-native";
import FBLogin from "react-native-facebook-login";
import UserActions from "../users/UserActions";
class LoginPage extends React.Component {
render() {
const { userData, onSuccessfulLogin } = this.props;
return (
<FBLogin
permissions={["email","user_friends"]}
onLoginFound= { data => {
onSuccessfulLogin(data.credentials);
}}
/>
)
}
};
export default LoginPage;
Container Component (LoginContainer.js)
import { connect } from 'react-redux';
import LoginPage from "../login/LoginPage";
import UserActions from "../users/UserActions";
const mapDispatchToProps = (dispatch) => {
return {
onSuccessfulLogin: (userData) => {
dispatch(UserActions.userLoggedIn(userData))
}
}
}
const mapStateToProps = (state) => {
return {
userData: state.userData
}
}
const LoginContainer = connect(
mapStateToProps,
mapDispatchToProps
)(LoginPage);
export default LoginContainer;
Also, if I wanted to make the updated state.userData accessible to the LoginPage component, how would I do that? Any help is appreciated!
Solved! When using ES6 classes, you're required to call super(props) in a constructor method in order to access the container's properties in the connected presentational component:
class LoginPage extends React.Component {
constructor(props){
super(props);
}
render(){
// ...
}
}
Your container component is supposed to be a component and it must have a render function with the dumb/presentational components you want to render.
import { connect } from 'react-redux';
import LoginPage from "../login/LoginPage";
import UserActions from "../users/UserActions";
class LoginContainer extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<LoginPage userData={this.props.userData}
onSuccessfulLogin={this.props.onSuccessfulLogin}
/>
)
}
};
const mapDispatchToProps = (dispatch) => {
return {
onSuccessfulLogin: (userData) => {
dispatch(UserActions.userLoggedIn(userData))
}
}
}
const mapStateToProps = (state) => {
return {
userData: state.userData
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(LoginPage);