peterp / react-native-tags

Tag input component for React Native
MIT License
288 stars 75 forks source link

Re-rendering view on initial tags change #65

Open EvansPie opened 4 years ago

EvansPie commented 4 years ago

Hey @peterp, first of all, awesome library 🙌

Maybe what I'm doing is out of the scope of this project. I've basically built a wrapper that the user can select/deselect a tag between a list of tags. Similar to setting your interests in various apps. Everything works perfectly apart from re-rendering the view on the initialTags prop change. I had a look at your code and it seems that it's like that by design.

I've solved my issue by re-setting the state tags when the props tags change.

componentDidUpdate(prevProps) {
    if (JSON.stringify(prevProps.initialTags) !== JSON.stringify(this.props.initialTags)) {
      this.setState({ tags: [...this.props.initialTags] });
    }
}

Is there another way to re-render the view?

Caminyx commented 4 years ago

Hi there, I used a state to conditionally render the component, like so :

import React, { FunctionComponent as Component, useState, useEffect } from "react"
import Tags from "react-native-tags"

export const Test: Component<TestProps> = props => {

    const [ displayedTags, setDisplayedTags ] = useState()

    const getTags = async () => {
        var myTags = await ... // Load your tags
        setDisplayedTags(myTags)
    }

    useEffect(() => {
        getTags()
    }, [])

    // You render the component only when displayedTags has been initialised
    return (
        <>
            { displayedTags &&
              <Tags
                initialTags={displayedTags}
                ...
              />
            }
        </>
    )
}

I only use TypeScript for React Native so I don't know the equivalent in plain RN, but you get the point. By using state, you can postpone the render of the Tags component as well as re-rendering it if needed.

bhagwat-karankar22 commented 3 years ago

@Caminyx its a work around for this issue, but it worked.

themavenhater commented 3 years ago

here's a work around i did :

const [ tags, setTags] = useState()

useEffect(() => {
    if(route.params.tags.length>0) setTags(route.params.tags)
    else {
         setTags([])
          }
}, [])

return (
    <>
        { Array.isArray(tags) &&
          <Tags
            initialTags={tags}
            ...
          />
        }
    </>
)