'how to change element that fits a component to an element that fits a function in react native

I am a new react native developer, I found a component and I want to use it in a function, but it is not clear to me how I would change it, can I get a help?

Here is the component

import TagInput from 'react-native-tag-input';

...

<TagInput
  value={this.state.emails}
  onChange={(emails) => this.setState({ emails })}
  labelExtractor={(email) => email}
  text={this.state.text}
  onChangeText={(text) => this.setState({ text })}
/>

I got the code from here https://bestofreactjs.com/repo/jwohlfert23-react-native-tag-input



Solution 1:[1]

you don't need to convert the component itself, you can use it as it is, but you need to change its implementation.

Basically, if you want to use function components, which is highly recommended now, you need to change the usage of the state in the component which will contain the <TagInput>.

Instead of using "this" which points to the class itself, you need to implement a hook called useState.

You can find it the docs here: https://reactjs.org/docs/hooks-state.html

Solution 2:[2]

I guess you are asking how to adapt the code to fit the functional component, which includes converting the this.setState.

React provides some thing called React hooks, which you can think of as a way to replace states and lifecycles. You can read more about it here here In your case, it would go like this:

import { useState } from 'react';
...
// useState can only be called inside functional components
const [emails, setEmails] = useState([]);
const [text, setText] = useState('');
...
<TagInput
  value={emails}
  onChange={(emailTags) => setEmails(emailTags)} // to avoid naming confusion
  labelExtractor={(email) => email}
  text={text}
  onChangeText={(inputText) => setText(inputText)}
/>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RamaProg
Solution 2 ZygD