Reputation: 19
how to add, element from a button react native, I want to create a project as seen in the image, but I don't know how to add an element from a button, add a div with two inputs and when saving start from the beginning.
Upvotes: 1
Views: 1084
Reputation: 125
I believe you can use an array as your state. And every time you can push your view in the array (when the user clicks plus in your example).
const SampleView = () => {
return (
<View style={{ flexDirection: 'row' }}>
<TextInput style={{ width: 200, height: 40, margin: 10 }} label="placeholder" />
<TextInput style={{ width: 200, height: 40, margin: 10 }} label="placeholder" />
</View>
);
};
......
........
const [views, setViews] = React.useState([]);
const addItems = () => {
const arr = [...views];
arr.push(<SampleView />);
setViews(arr);
};
Finally, you can render the array items.
<View style={styles.container}>
{views.map((item, index) => {
return (
<View style={{ padding: 10}}>
<Text>item : {index}</Text>
{item}
</View>
);
})}
<Button onPress={addItems}>
<Text>Add</Text>
</Button>
</View>
Here is a snack link for you to get the full idea. https://snack.expo.io/@saad-bashar/dynamic-elements
Upvotes: 2