I am using react native and redux. Now I want to create a dynamic component, for example a dropdown component. I pass a state via props which works fine but to make this component re-usable I have to call the right dispatch function for this state. I am not sure if that is the right way to do. I am only working with react for a week now ;)
For the sake of simplicity a simple text field component:
import React, {Component} from 'react';
import {Button, StyleSheet, Text, TextInput, View} from 'react-native';
import allActions from '../../actions/allActions';
import {useDispatch, useSelector} from 'react-redux';
function Name (props) {
const dispatch = useDispatch();
const componentState = props.state;
/**
* Save the new user to the state
* @param text
*/
const handleChange = (text) => {
// here I want to call the action dynamically
// e.g. allActions.userActions.MY_VARIABLE_PASSED_THROUGH_PROPS
dispatch(allActions.userActions.setUser(text));
}
return (
<View>
<TextInput
style={styles.input}
defaultValue={componentState}
onChangeText={handleChange}
/>
</View>
);
}
export default Name;
I pass the state when I instatiate the component
<Name state={ store.getState().user.name } action={my_action_to_call}/>
EDIT: This is my userAction
import * as actions from '../actionTypes';
const setUser = (userObj) => {
return {
type: actions.SET_USER,
payload: userObj
}
}
const setGender = (userObj) => {
return {
type: actions.SET_GENDER,
payload: userObj
}
}
export default {
setUser,
setGender
}
Don't worry! That is right. for making dynamic components in react you do have to pass values and fuction via props. Your actions are fuctions, so easily you can pass your function and call it in your component. If I were you, I would definitely do that. like:
const nameAction = (name) => {
return {
type: SET_NAME,
payload: name
}
}
<Name state={ store.getState().user.name } action={nameAction}/>
I figured it out:
Component call
<Dropdown title={'Gender'} placeholder={'Select your gender'} action={userActions.setGender} state={ store.getState().user.gender } data={gender_data} />
and here is the handleChange function:
const handleChange = (e) => {
let action = _props.action(e.value);
dispatch(action);
}