0
import React,{useState} from 'react'
import App from './App'
const AppList = ()=>{
    const [arr,addElement] = useState([1])
    const handleClick = ()=>{
        arr.push(1)
        addElement(arr)
    }
    return(
       <>
        {
            arr.map((elements)=>{
                return <h1>{elements}</h1>
            })
        }   
        <button onClick={handleClick}>add</button>
       </>
    )
}
export default AppList

I tried to add elements and render. the items are getting added in array but its not getting rendered in browser.

2 Answers 2

1

React is checking state updates by reference, since you provide the same array reference the component is not going to re-render.

Instead, make an immutable update

const AppList = () => {
  const [arr, addElement] = useState([1])

  const handleClick = () => {
    addElement(prevState => [...prevState, 1])
  }

  return (
    <>
      {arr.map(element => (
        <h1>{element}</h1>
      ))}
      <button onClick={handleClick}>add</button>
    </>
  )
}

You also need to provide a unique key when rendering arrays, but don't use index as key since it can cause problems when adding and removing items from the array. You don't have anything unique here so you will need to think of a way of solving it. You can find more info about it here

Sign up to request clarification or add additional context in comments.

Comments

0

to rerender somthing in React you need to change the state, the best way to do it is to pass NEW array to the state, Thats why you have the setState method. So, you just need:

import React,{useState} from 'react'
import App from './App'
const AppList = ()=>{
    const [arr,setArray] = useState([1])
    const handleClick = ()=>{
        let newArr = [...arr,1]
        setArray(newArr)//setArray will be a better name.
    }
    return(
       <>
        {
            arr.map((elements)=>{
                return <h1>{elements}</h1>
            })
        }   
        <button onClick={handleClick}>add</button>
       </>
    )
}
export default AppList

2 Comments

can't we do this adding element in old array and then passing that
No, because in the mind of React you didn't change anything so there is no need to rerender.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.