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}/>
CodePudding user response:
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.
CodePudding user response:
umm actually, we always uses class instead of function when coding react, so that it can do many many things instead.Then you can do dispatch as your code, like:
export default class myApp extends Component<Props>{
render(){
return “HTML Code Here”
}
}
And Register it as :
import { AppRegistry } from “react-native”
AppRegistry.register(“your file name”, () => myApp)