Search code examples
javascriptreactjsarraysrender

New card not rendering in react


I added a feature whereby the user can add cards to the app with the following code:

export default function Filter({
   onChangeHogListAdd
   }) {

const [textInput, setTextInput] = useState('')

function handleAdd() {
    onChangeHogListAdd(textInput)
}

return(
   <div>
        <div className ='ui item'>
            <label>Add a hog!</label>
        </div>
        <div className='ui item'>
            <input
                className='ui input focus'
                type='text'
                placeholder='Add hog...'
                onChange={(e) => setTextInput(e.target.value)}
            />
        </div>
        <div className='ui item'>
            <button className='ui button' onClick={handleAdd}>Add</button>
        </div>
   </div>
)

The callback prop in the parent component is the following

function hogListAdd(newName) {
    hogList.push({ name : newName })
}

Whereby hogList is an array of objects which is rendered as cards on the UI. Weirdly enough, when a user adds a new hog through the text input box, the array hogList updates with the newly added object, but the page doesn't render it in. This is the part that I am stuck on, any help would be appreciated. Thank you.


Solution

  • You are pushing to hogList, which doesn't tell React about state change. In the parent component use useState hook and call the setter

    const [hogList, setHogList] = useState([]);
    function hogListAdd(newName) {
      setHogList((old) => [...old, { name : newName }]);
    }