0
export default function RenderPages({storage, setStorage, state, setState}){
const elRefs=[]
for(let i=0; i<storage[state.currentFolderId][state.currentFileId].content.length; i++){
    elRefs.push(useRef())
}

return (
    <>
    {
      renderable
      ?<div className="writing">
        {storage[state.currentFolderId][state.currentFileId].content.map((page, index)=>
        <div className='textarea'>
          <textarea ref={elRefs[index]} placeholder='write here' value={page} id={"page"+index} onChange={(e)=>onChange(e, index)} rows={rows} cols={cols}></textarea>
        </div>)}
      </div>
      : <></>
    }
    </>
  )
}

I want to attach multiple ref to random number of "textarea" element. the number of element would be determined by the variable, "storage", which is given as props. I got error with above code. Help me please.

moaksan
  • 13
  • 2

2 Answers2

1

you don't need to use for loop to push the elements in ref, you already use map in return you can push textarea elements using ref like this way as you can see the below code, I hope this works. thanks

import { useRef } from "react";

export default function RenderPages({storage, setStorage, state, setState}) {
  const elRefs = useRef([]);

  return (
    <>
      {renderable ? (
        <div className="writing">
          {storage[state.currentFolderId][state.currentFileId].content.map((page, index) => (
            <div className="textarea">
              <textarea
                ref={ref => {
                  elRefs.current[index] = ref
                }}
                placeholder="write here"
                value={page}
                id={'page' + index}
                onChange={e => onChange(e, index)}
                rows={rows}
                cols={cols}></textarea>
            </div>
          ))}
        </div>
      ) : (
        <></>
      )}
    </>
  );
}
Ahmad Faraz
  • 1,371
  • 1
  • 4
  • 11
0
const myRefs = useRef([])
ref={ref => myRefs.current[index] = ref} // <--- Right syntax
Duy Tran
  • 356
  • 3
  • 6