Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 725
Guilherme Cavenaghi Avatar asked Dec 07 '21 13:12

Guilherme Cavenaghi


People also ask

How to bind form input to a component?

In one way binding, Running events listening from input entered in the form and ready to pass to component. Update the form input value from once the component change its value. The below is an example for reading the input text value on button click.

What is the use of V model in form input?

Form Input Value Binding is handled by the v-model directive that helps to bind the static strings, to simplify the input value binding. The v-model can be used on different types of elements like input, textarea, checkbox, radio, and select.

How to get an input textbox value without wrapping the input element?

There are several methods are used to get an input textbox value without wrapping the input element inside a form element. Let’s show you each of them separately and point the differences. The first method uses document.getElementById ('textboxId').value to get the value of the box:

What is the use of input form in angular?

Form contains multiple html input elements to take input from the user. button allows the user to submit the from to backend API an d it calls click binding event. In Angular, View is html template and controller is an typescript component. Reading input text is basic concept every Angular developer need to know.


Video Answer


2 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.

like image 169
user9747 Avatar answered Oct 20 '22 20:10

user9747


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} />
};
like image 36
Dawid Avatar answered Oct 20 '22 20:10

Dawid