How to pass State with context Api react?

Viewed 412

First I created a .js file and created context.

In app.js

export default function App({ navigation }) {
    const [ItemURL,setItemURL] = useState('URL')

    return (
        <ItemContext.Provider value={ItemURL}>
            ...
        </ItemContext.Provider>
    )
}

now I want to pass my setItemURL to my child component

So I tried.

export default const ItemsComponent = (props) => {
    const [URL, setURL] = useContext(ItemContext)
    return(
       <TouchableWithoutFeedback
                onPress={() => {
                    setURL(props.Json.Image)
                }}
            />
    )
}

but its not working and saying setURL is not a function(in setURL(props.Json.Image)) ,setURL is 'R'

1 Answers

You should actually pass the setURL function in the context value as well.

export default function App({ navigation }) {
  const [ItemURL, setItemURL] = useState('URL');

  const value = [ItemURL, setItemURL];

  return (
    <ItemContext.Provider value={value}>
      ...
    </ItemContext.Provider>
  )
}
Related