Home > Blockchain >  how handle multiple inputs thats created dynamically from object react native
how handle multiple inputs thats created dynamically from object react native

Time:04-08

i have a file contain objects data.js.

components: [
      {
        id: "1",
        nameC: "name",
        type: "TextInput",
        options: { placeholder: "saisir nom", required: true },
      },
      {
        id: "2",
        nameC: "Phone",
        type: "Phone",
        options: { placeholder: "saisir number", required: false },
      },
      {
        id: "3",
        nameC: "name",
        type: "TextInput",
        options: { placeholder: "saisir nom", required: true },
      },

i got those objects to create inputs Dynamically in this file TemplateScreen.js .

<>
        {getData.length === 0 ? (
          <Empty />
        ) : (
          getData.map((item, index) => {
            switch (item.type) {
              case "TextInput":
                return (
                  <>
                    <InputText
                      ModuleName={item.nameC}
                      placeholder={item.options.placeholder}
                      required={item.options.required}
                    />
                  </>
                );
              case "Phone":
                return (
                  <>
                    <Phone
                      ModuleName={item.nameC}
                      placeholder={item.options.placeholder}
                      required={item.options.required}
                    />
                  </>
                );
              default:
                return <Text>Nothing hear</Text>;
            }
          
          })
        )}
      </>

i render inputs successfully but i'can't handle those inputs :( .i'm tried many methods but anyone worked for me.i am tried many tricks from reactjs tuto but nothing worked for me .i'm blocked 4 days in this problem,please anyone can help me :(

this file contain TextInput component, i am called it in templateScreen.js Phone component is the same as TextInput component with a bit of difference

export const InputText = (props) => {
  const [state, setState] = React.useState("");
  
  return (
    <View style={styles.container} key={props.keys}>
      <View style={styles.Namecontainer}>
        <Text style={styles.moduleName}>{props.ModuleName}</Text>
        {props.required ? <Text style={styles.required}>*</Text> : <></>}
      </View>
      <TextInput
        {...props}
        value={state}
        onChangeText={(text) => setState(text)}
        placeholder={props.placeholder}
        style={styles.inputtext}
      />
    </View>
  );
};```


CodePudding user response:

Instead of placing state inside the Input text and Phone text component, why not just use useRef hook inside the template screen js? We should generate refs depending on the length of the data, thus

const inputRefs = getData.reduce((acc,curr)=>{
    const ref = useRef(“”);
    acc[curr.nameC] = ref;
    return acc:
}, {});

this will generate refs for each of your inputs. Now in our map method, we just place our input refs to each ex:

<InputText
   inputRefs[item.nameC]
   ModuleName={item.nameC}
   placeholder={item.options.placeholder}
   required={item.options.required}
 />

In order to get their values, map the inputRefs and try console.log(inputRef.current) to see.

CodePudding user response:

I have created the replica in reactjs because react-native is not set up on my PC but the logic remains the same, as I correctly understand what you wanna do is render dynamic input form according to the data this is provided to you and store the value in the state

import React, { useEffect, useState } from "react";

const components = [
  {
    id: "1",
    nameC: "name",
    type: "TextInput",
    options: { placeholder: "saisir nom", required: true },
  },
  {
    id: "2",
    nameC: "phone",
    type: "Phone",
    options: { placeholder: "saisir number", required: false },
  },
  {
    id: "3",
    nameC: "city",
    type: "TextInput",
    options: { placeholder: "saisir nom", required: true },
  },
];

const DynamicInput = () => {
  const [field, setField] = useState();

  const handleChange = (event) => {
    setField({ ...field, [event.target.name]: event.target.value });
  };

  useEffect(() => {
    let obj = {};
    components.forEach((item, index) => {
      obj = { ...obj, [item.nameC]: "" };
    });
    setField(obj);
  }, []);

  console.log(field)

  return (
    <div>
      {!field ? (
        <div>Loading...</div>
      ) : (
        components.map((item) => {
          const value = field[item.nameC];
          switch (item.type) {
            case "TextInput":
              return (
                <InputText
                  key={item.nameC}
                  value={value}
                  onChangeHandler={handleChange}
                  placeholder={item.options.placeholder}
                  isRequired={item.options.required}
                  name={item.nameC}
                />
              );
            case "Phone":
              return <div key={item.nameC}>This will be same as input</div>;
            default:
              return <div key={item.nameC}>Nothing hear</div>;
          }
        })
      )}
    </div>
  );
};
export default DynamicInput;
export const InputText = ({
  value,
  onChangeHandler,
  placeholder,
  isRequired,
  name,
}) => {
  return (
    <input
      value={value}
      name={name}
      onChange={onChangeHandler}
      placeholder={placeholder}
      required={isRequired}
    />
  );
};

  • Related