简体   繁体   中英

how to change text to input field onclick in react?

I want to change the Text to input field when clicking on edit button. The Text is inside map function, The Code that I have worked is mentioned below

function test() {
  const [img, setImg] = useState(false)

  let data = {
    {  
      id: 1,
      name: 'test 1'
    },
    {
      id: 2,
      name: 'test 2'
    }
  }

return (
  <>
    {data.map(e => {
      return (
        {img ? (
          <input placeholder={e.name} />
        ) : (
          <div>
            <p>{e.name}</p>
            <button onClick={() => setImg(true)}>edit</button>
          </div>
        )}
      )
    })}
  </>
)

In this code if i click on edit button, it actually shows input in all name, rather than which i click. i want to edit only one name, for example, if i want to edit name test 1 , i dont want the input to show on test 2

Something like this would work -

function test() {
  const [img, setImg] = useState(-1)

  let data = {
    {  
      id: 1,
      name: 'test 1'
    },
    {
      id: 2,
      name: 'test 2'
    }
  }

return (
  <>
    {data.map((e, idx) => {
      return (
        {img==idx ? (
          <input placeholder={e.name} style={{display: idEdit == e.id ? 'block' : 'none'}}/> //<== Conditionaly to appear or not
        ) : (
          <div>
            <p>{e.name}</p>
            <button onClick={() => {
               setImg(idx)
              } 
             }>edit</button>
          </div>
        )}
      )
    })}
  </>
)

You can set a state when you click edit button, then use this state to conditionally show of input you want:

function test() {
  const [img, setImg] = useState(false)
  const [idEdit, setIdEdit] = useState(null); //<== Create this state

  let data = {
    {  
      id: 1,
      name: 'test 1'
    },
    {
      id: 2,
      name: 'test 2'
    }
  }

return (
  <>
    {data.map(e => {
      return (
        {img ? (
          <input placeholder={e.name} style={{display: idEdit == e.id ? 'block' : 'none'}}/> //<== Conditionaly to appear or not
        ) : (
          <div>
            <p>{e.name}</p>
            <button onClick={() => {
               setImg(true)
               setIdEdit(e.id) //<== set idEdit state here
              } 
             }>edit</button>
          </div>
        )}
      )
    })}
  </>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM