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.

3
  • What error are you getting ? Commented Jul 25, 2022 at 14:20
  • 1
    Maybe possible duplication ? The answer is here - stackoverflow.com/a/54633947/5618326. Commented Jul 25, 2022 at 14:20
  • This error. "React Hook "useRef" may be executed more than once. Possibly because it is called in a loop. React Hooks must be called in the exact same order in every component render" Commented Jul 25, 2022 at 14:26

2 Answers 2

2

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>
      ) : (
        <></>
      )}
    </>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

0
const myRefs = useRef([])
ref={ref => myRefs.current[index] = ref} // <--- Right syntax

Comments

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.