Search code examples
react-nativetagsreact-component

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

  • 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)}
    />