Home > OS >  Add item to list inside component by outside function in React
Add item to list inside component by outside function in React

Time:05-25

How is possible update a hooked list inside a component using an external function? to be clear, suppose the pseudo-code:

list.tsx

const lists = () => {

const [list, setlist] = useState([]);

return <>
          The fruits are:
          { list.map( x => <>x.name<br /></> ) }
       </>

}

export { lists }

index.tsx

import { lists } from './list'
...
<Lists /> 
<button onClick={ () => lists.setlist.push({name: 'banana'}) }>Add Banana</button>

Any research tips are welcome.

I tried some solutions like using "static" and export a function inside a class but no sucess.

CodePudding user response:

list.tsx

const lists = ({ list }) => {

return <>
          The fruits are:
          { list.map( x => <>x.name<br /></> ) }
       </>

}

index.tsx

const [list, setlist] = useState([]);

...
<Lists list={list} /> 
<button onClick={ () => setlist(prev => [..prev, {name: 'banana'}]) }>Add Banana</button>

State in child

list.tsx

const lists = ({listsRef}) => {

const [list, setlist] = useState([]);

useEffect(() => {
  listsRef.current = (callback) => setlist(prev => callback(prev))
}, [])

return <>
          The fruits are:
          { list.map( x => <>x.name<br /></> ) }
       </>

}

index.tsx


const listsRef = useRef(null)

...
<Lists listsRef={listsRef} /> 
<button onClick={ () => listsRef.current(prev => [..prev, {name: 'banana'}]) }>Add Banana</button>

CodePudding user response:

The easiest way it to use the useContext hook, then all the child elements of the <context.Provider></context.Provider> tags will have access to the top level state

  • Related