Home > Software engineering >  New card not rendering in react
New card not rendering in react

Time:08-28

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.

CodePudding user response:

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 }]);
}

CodePudding user response:

If you want to re render the ui with updated array then you have to store it in a state and update in your function. It can look like this

function hogListAdd(newName) {
    setHogList([{name : newName }, ...hogList])
    //hoglist is your state variable
}

Use the state where you hoglist is present so that on any change to it the component will re render.

And use that state to render ui so that your component depends on it.

Hope this helps!!

  • Related