1

picture of app

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.