How can I get values from input components (study purposes)?

Viewed 301

My problem is that I'm trying to handle the value of my inputs, which the user defines which input he wants, by an API call.

Here is where I get the values :

 const handleClick = buttonTitle => async () => {
    await renderField(buttonTitle).then(response => {               
      navigation.navigate('FormScreen', {
        collectionKey: buttonTitle.slice(7),
        paramKey: JSON.stringify(response),
      });     
  });
  };

Render field is an API call, which returns me {"message": [{"_id": "618e4c23db08f70b719f3655", "author": "adicionarei posteriormente", "ceatedAt": "2021-11-12 08:12:32", "field": "abc", "fieldtype": "Text"}, {"_id": "618e4c9ddb08f70b719fae37", "author": "adicionarei posteriormente", "ceatedAt": "2021-11-12 08:14:35", "field": "Animal", "fieldtype": "Text"}]}

Then I have my Form component, where I get some components in need and display for the user:

const FormScreen = ({route, navigation}) => {
  return (
    <Container>
      <InputBody route={route.params.paramKey} navigation={navigation} />
    </Container>
    // => handle submit Input it in here ?
  );
};

For my inputbody component I have the following code (remembering that (body.map is the api call response):

  return (
    <>   
    {Object.keys(Body).length > 0 ? (     
      Body.map(item => (
        <React.Fragment key={uuid.v4()}><Texto>{item.field}</Texto>  
           {renderContent(item.fieldtype,item.field)}
        </React.Fragment>
      ))
    ) : (
      <ActivityIndicator size="large" color="#eb6b09" />
    )}
    </>
  )
}

Then I have my renderContent( where I get the type of the field as a string and the name of the field that is a string as well).

function renderContent(type,field) {
    switch(type) {     
      case 'Numeric':
      return <NumberInput key={field} keyboardType="numeric" />
     case 'Text':
      return <TextInput key={field} />
    }
  }

Remembering that: each field type can appear more than once. (For example: I can have one form with more than 1 Text input), then my question is: how can I handle the values of my input knowing that it can have any kind of input(Numeric or Text) ?

obs: I can show any kind of information.

3 Answers

    const Input = ({value,keyboardType,onChange})=>{
      return(
        <TextInput value={value} keyboardType={keyboardType} onChangeText={onChange} /> 
      )
    }


    const [payload,setPayload] = useState({});

    const onValue=(e,field)=>{
      let tempPayload = {...payload};
      tempPayload[field] = e;
      setPayload(tempPayload)
    }


    const renderComponent = (fieldObj)=>{
      switch(fieldObj.type):
        case "Text":
          return <Input keyboardType="default" onChange={(e)=>onValue(e,fieldObj.field)} value={payload[fieldObj.field]||""}/>
        case "Number":
          return <Input keyboardType="numeric" onChange={(e)=>onValue(e,fieldObj.field)} value={payload[fieldObj.field]||""} />
        case "Dropdown":
          return <Dropdown options={fieldObj.options} />  //if you want to add dropdown, radio buttons etc in future
    }

The idea is pretty straight forward. Store the values from the form fields in a object payload. The name is name of the field eg. Animal. The value is the value of that field. You can also initialize the object with all the keys and their values as empty or a default value that you get from the api. So if the fields we have rendered is Animal and Car. The payload will be

{
  'Animal':'Tiger',
  'Car':'BMW'
}

This is handled using the onValue function. You can also add validation in this function.For example if you pass a regex with your api for that field, the you can validate the value using the regex.

It was a bit hacky so I simplified it, I think you should understand the logic behind it.

import React, { useState } from 'react';
import { TextInput } from 'react-native';

const createInitialState = (inputList) => {
  return inputList.reduce((accumulator, currentValue) => {
    return {
      ...accumulator,
      [currentValue.field]: '',
    };
  }, {});
};


const SomeScreen = () => {
  const initialDataPassed = [
    {
      '_id': '618e4c23db08f70b719f3655',
      'author': 'adicionarei posteriormente',
      'ceatedAt': '2021-11-12 08:12:32',
      'field': 'abc',
      'fieldType': 'Text',
    }, {
      '_id': '618e4c9ddb08f70b719fae37',
      'author': 'adicionarei posteriormente',
      'ceatedAt': '2021-11-12 08:14:35',
      'field': 'Animal',
      'fieldType': 'Text',
    },
    {
      '_id': '618e4c9ddb08f70b719fae37',
      'author': 'adicionarei posteriormente',
      'ceatedAt': '2021-11-12 08:14:35',
      'field': 'Animal',
      'fieldType': 'Number',
    },
  ];

  return (
    <Form inputList={initialDataPassed} />
  );
};

const Form = ({ inputList }) => {
  const [formState, setFormState] = useState(createInitialState(inputList));

  return (
    <>
      {inputList.map((item) => {
        const handleTextInputValueChange = (text) => {
          // this is solution is better if we base on old value
          setFormState(oldState => ({
            ...oldState,
            [item.field]: text
          }))
        };

        return <Input key={item.field} value={formState[item.field]} onChangeText={handleTextInputValueChange} fieldType={item.fieldType} />
      })}
    </>
  );
};


const Input = ({value, onChangeText, fieldType}) => {
  const keyboardType = fieldType === 'Number' ? 'numeric' : undefined;

  return <TextInput value={value} keyboardType={keyboardType} onChangeText={onChangeText} />
};

If you just want this input types, you could do in this way:

First, define and object for mapping your field types to html input types:

const inputTypesMapper = {
  Numeric: "number",
  Text: "text",
  Boolean: "checkbox"
};

And thus you can render them as follow:

<div className="App">
 {data.message.map(({ fieldtype, field }) => (
   <input type={inputTypesMapper[fieldtype]} defaultValue={field} />
 ))}
</div>

Here you go an example

But if you want to render different components for each field type, you could do as follow:

First, define and object for mapping your field types to html input types:

const inputTypesMapper = {
  Text: ({ value }) => {
    return <input type={"text"} defaultValue={value} />;
  },
  MultipleOptions: ({ value }) => {
    return (
      <select>
        {value.map(({ id, value }) => {
          return <option value={id}>{value}</option>;
        })}
      </select>
    );
  }
};

And thus you can render them as follow:

  return (
    <div className="App">
      {data.message.map(({ fieldtype, field }) => {
        const renderInput = inputTypesMapper[fieldtype];

        return renderInput({ value: field });
      })}
    </div>
  );

Here you go an example

Related