Lama
Lama

Reputation: 67

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

Upvotes: 0

Views: 389

Answers (2)

RamaProg
RamaProg

Reputation: 1387

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

Upvotes: 1

nxthai2910
nxthai2910

Reputation: 26

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

Upvotes: 1

Related Questions