I have seen similar questions but none of the answers are working in my case and I hope someone will be able to tell me why.
My ReactApp renders 3 card components that flip when clicked on. The cards are populated with data from an object array and is rendered with a map function (added info in case it has an impact). Here is parent component.
import React from 'react'
import FlipCard from './FlipCard'
const cards = [
{
id: 1,
text: 'NOPE',
},
{
id: 2,
text: '!!WINNER!!',
},
{
id: 3,
text: 'NOPE',
},
]
const shuffleCards = array => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
const temp = array[i]
array[i] = array[j]
array[j] = temp
}
return array
}
shuffleCards(cards)
console.log(cards)
const CardGameUI = () => {
shuffleCards(cards)
return (
<div className="cards-ui">
{cards.map(card => (
<FlipCard key={card.id} text={card.text} value={card.id} />
))}
</div>
)
}
export default CardGameUI
When one of the cards are flipped, I need the onClick for the other cards to be disabled. I tried using state and a conditional in my onClick event but it has no effect. The according to the console.log, the state of the play boolean is changed and if I manually change the conditional in the onCLick event check if play is true, then it works perfectly fine. I am clearly missing something because it seems as though the conditional is working and the state is changing.
import React, { useState } from 'react'
import ReactCardFlip from 'react-card-flip'
import FrontComponent from './FrontComponent'
import BackComponent from './BackComponent'
const FlipCard = ({ text, value }) => {
const [isFlipped, setIsFlipped] = useState(false)
const [activeCard, setActiveCard] = useState(2)
const [play, setPlay] = useState(false)
console.log(play.valueOf())
function handleFlip() {
setPlay(true)
setIsFlipped(!isFlipped)
console.log(isFlipped)
setActiveCard(value)
console.log(value)
}
if (activeCard !== 2) {
console.log('Play again?')
}
return (
<>
<ReactCardFlip isFlipped={isFlipped} flipDirection="horizontal">
<FrontComponent onClick={!play ? handleFlip : null} />
<BackComponent text={text} value={value} />
</ReactCardFlip>
</>
)
}
export default FlipCard
What am I missing?
You should manage the onClick event and the flip state on the parent instead of inside the card.
An high-level overview will be:
const CardGameUI = () => {
const [flipped, setFlipped] = useState({});
const hasFlipped = Object.values(flipped).includes(true);
const handleFlip = id => () => setFlipped(flipped => ({
...flipped,
[id]: true // can be changed to toggle in case you need it in the future
}));
return (
<div>
{cards.map(({ id, text }) => (
<FlipCard
key={id}
text={text}
value={id}
onFlip={handleFlip(id)}
flipped={flipped[id]}
disabled={hasFlipped}
/>
))}
</div>
)
};
const FlipCard = ({ text, value, onFlip, flipped , disabled}) => {
return (
<ReactCardFlip isFlipped={flipped} flipDirection="horizontal">
<FrontComponent onClick={onFlip} disabled={disabled} />
<BackComponent text={text} value={value} />
</ReactCardFlip>
)
}
I have React component where I can dynamically add new text inputs. So, I need to push the values from the inputs to array.
Can anyone help me how to do this?
Here is my code:
function FormPage({ setData }) {
const [item, setItem] = useState([]);
const [counter, setCounter] = useState(0);
const handleCounter = () => {
setCounter(counter + 1);
};
const addItem = (setItem) => setItem((ing) => [...ing, newItem]);
return (
{Array.from(Array(counter)).map((c, index) =>
<TextField
key={index}
label="Item"
onChange={() => setItem(i=> [...i, (this.value)])}
/>
)}
<Button onClick={handleCounter}>Add one more item</Button>
)
}
Here is example in sandbox:
https://codesandbox.io/s/solitary-sound-t2cfy?file=/src/App.js
Firstly, you are using two-way data binding with your TextField component, so you also need to pass a value prop.
Secondly, to get the current value of TextField, we don't use this.value. Rather, the callback to onChange takes an argument of type Event and you can access the current value as follows
<TextField
...
onChange={(e) => {
const value = e.target.value;
// Do something with value
}}
/>
You cannot return multiple children from a component without wrapping them by single component. You are simply returning multiple TextField components at the same level, which is also causing an error. Try wrapping them in React.Fragment as follows
...
return (
<React.Fragment>
{/* Here you can return multiple sibling components*/}
</React.Fragment>
);
You are mapping the TextField components using counter which is equal to the length of item array. In handleCounter, we'll add a placeholder string to accomodate the new TextField value.
...
const handleCounter = () => {
setCounter(prev => prev+1); // Increment the counter
setItem(prev => [...prev, ""]); // Add a new value placeholder for the newly added TextField
}
return (
<React.Fragment>
{ /* Render only when the value of counter and length of item array are the same */
counter === item.length && (Array.from(Array(counter).keys()).map((idx) => (
<TextField
key={idx}
value={item[idx]}
label="Item"
onChange={(e) => {
const val = e.target.value;
setItem(prev => {
const nprev = [...prev]
nprev[idx] = val;
return nprev;
})
}}
/>
)))}
<br />
<Button onClick={handleCounter}>Add one more item</Button>
</React.Fragment>
);
Here is the sandbox link
Try this:
import "./styles.css";
import React, { useState } from "react";
export default function App() {
// Changes made here
const [item, setItem] = useState({});
const [counter, setCounter] = useState(0);
console.log("item 1:", item[0], "item 2:", item[1],item);
const handleCounter = () => {
setCounter(counter + 1);
};
const addItem = (newItem) => setItem((ing) => [...ing, newItem]);
return (
<>
{Array.from(Array(counter)).map((c, index) => (
<input
type="text"
key={index}
//Changes made here
value={item[index]}
label="Item"
// Changes made here
onChange={(event) => setItem({...item, [index]:event.target.value })}
/>
))}
<button onClick={handleCounter}>Add one more item</button>
</>
);
}
Instead of using an array to store the input values I recommend using an object as it's more straight-forward.
If you wanted to use an array you can replace the onChange event with the following:
onChange={(event) => {
const clonedArray = item.slice()
clonedArray[index] = event.target.value
setItem(clonedArray)
}}
It's slightly more convoluted and probably slightly less optimal, hence why I recommend using an object.
If you want to loop through the object later you can just use Object.entries() like so:
[...Object.entries(item)].map(([key, value]) => {console.log(key, value)})
Here's the documentation for Object.entries().
codeSolution: https://codesandbox.io/s/snowy-cache-dlnku?file=/src/App.js
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [item, setItem] = useState(["a", "b"]);
const handleCounter = () => {
console.log(item, "item");
setItem([...item, ""]);
};
const setInput = (index) => (evt) => {
item.splice(index, 1, evt.target.value);
setItem([...item]);
};
return (
<>
{item.map((c, index) => {
return (
<input
type="text"
key={index}
label="Item"
value={c}
onChange={setInput(index)}
/>
);
})}
<button onClick={handleCounter}>Add one more item</button>
</>
);
}
I have solved for you . check if this works for you , if any issues tell me
I have a strange issue with passing a function as a prop in my React app. Code as follows:
const NewPage = () => {
const [blocks, setBlocks] = useState([]);
const [needsShowImageModal, setNeedsShowImageModal] = useState(false);
const textButtonHandler = () => {
const key = randomInt(0, 1000000000);
const array = blocks.concat({ key, deleteButtonHandler: deleteButtonHandler });
setBlocks(array);
};
function deleteButtonHandler(blockKey) {
// Test functionality, if one text field was added arrray size should
// be 1
console.log(blocks.length);
}
return (
<div>
<ImageModal
show={needsShowImageModal}
onHide={() => setNeedsShowImageModal(false)}
insertButtonHandler={insertImageHandler}
/>
<div className="d-flex">
<NewPageSidebar
textButtonHandler={textButtonHandler}
imageButtonHandler={imageButtonHandler}
spacingButtonHandler={spacingButtonHandler}
/>
<NewPageContent blocks={blocks} />
</div>
</div>
);
};
export default NewPage;
When text button handler is called (a button press) I add a new data model to the blocks array. I have another button handler deleteButtonHandler that is passed to the NewPageContent component (inside the data model). NewPageContent:
const NewPageContent = ({ blocks }) => {
return (
<div className="new-page-content-container border mr-5 ml-5 p-3">
{blocks.map(block =>
<TextBlock
key={block.key}
blockKey={block.key}
deleteButtonHandler={block.deleteButtonHandler}
/>
)}
</div>
);
};
NewPageContent.propTypes = {
blocks: PropTypes.arrayOf(PropTypes.element)
};
export default NewPageContent;
And finally this handler is passed to TextBlock:
const TextBlock = ({ deleteButtonHandler, blockKey }) => {
const [editorState, setEditorState] = useState(
() => EditorState.createEmpty(),
);
const toolbarClickHander = (buttonType, e) => {
e.preventDefault();
switch (buttonType) {
case 'delete':
// Delete button handler called here
deleteButtonHandler(blockKey);
break;
default:
break;
}
};
return(
<div className='text-block'>
<TextBlockToolbar clickHandler={toolbarClickHander} />
<Editor
editorState={editorState}
onChange={setEditorState}
/>
</div>
);
};
If I add one element to blocks via textButtonHandler the component is rendered on screen as expected. However if I tap the delete button and deleteButtonHandler is called it will log the size of the array as 0, Strangely if I add second element and then tap the delete button for that element if logs the array size as 1. It's almost as if it's taking a snapshot of the blocks state just as the new textButtonHandler is assigned to the prop and not using the actual current state of blocks. Any ideas what I might be doing wrong here? Haven't run into this issue before. Thanks
Okay. What is happening here:
You passing a function in an object. That object might have an own context, and you tryes to use that function in that object context, what confuses react. (I know that ECMAScript simple objects has no own context, but react might process that data, so might work in different way .) So, pass each function standalone prop in the child component.
Example: https://codesandbox.io/s/broken-waterfall-vgcyj?file=/src/App.js:0-1491
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [blocks, setBlocks] = useState([
{ key: Math.random(), deleteButtonHandler }
]);
const textButtonHandler = () => {
const key = Math.random();
// const array = blocks.concat({
// key,
// deleteButtonHandler: deleteButtonHandler
// });
setBlocks(prev => prev.concat({ key, deleteButtonHandler }));
};
const deleteButtonHandler = blockKey => {
// Test functionality, if one text field was added arrray size should
// be 1
console.log(blocks.length);
};
return (
<div>
<div className="d-flex">
<NewPageContent
deleteButtonHandler={deleteButtonHandler}
blocks={blocks}
/>
</div>
<button onClick={textButtonHandler}>Handler</button>
</div>
);
}
const NewPageContent = ({ blocks = [], deleteButtonHandler = () => null }) => {
return (
<div className="new-page-content-container border mr-5 ml-5 p-3">
{blocks.map(block => (
<TextBlock
key={block.key}
blockKey={block.key}
// deleteButtonHandler={block.deleteButtonHandler}
deleteButtonHandler={deleteButtonHandler}
/>
))}
</div>
);
};
const TextBlock = ({ deleteButtonHandler = () => null, blockKey = "" }) => {
return (
<div className="text-block">
{blockKey}
<span onClick={deleteButtonHandler}>X</span>
</div>
);
};
I have consoled out your old solution, to compare it.
As far as I understood I can use refs for a single element like this:
const { useRef, useState, useEffect } = React;
const App = () => {
const elRef = useRef();
const [elWidth, setElWidth] = useState();
useEffect(() => {
setElWidth(elRef.current.offsetWidth);
}, []);
return (
<div>
<div ref={elRef} style={{ width: "100px" }}>
Width is: {elWidth}
</div>
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<div id="root"></div>
How can I implement this for an array of elements? Obviously not like that: (I knew it even I did not try it:)
const { useRef, useState, useEffect } = React;
const App = () => {
const elRef = useRef();
const [elWidth, setElWidth] = useState();
useEffect(() => {
setElWidth(elRef.current.offsetWidth);
}, []);
return (
<div>
{[1, 2, 3].map(el => (
<div ref={elRef} style={{ width: `${el * 100}px` }}>
Width is: {elWidth}
</div>
))}
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I have seen this and hence this. But, I'm still confused about how to implement that suggestion for this simple case.
As you cannot use hooks inside loops, here is a solution in order to make it work when the array changes over the time.
I suppose the array comes from the props :
const App = props => {
const itemsRef = useRef([]);
// you can access the elements with itemsRef.current[n]
useEffect(() => {
itemsRef.current = itemsRef.current.slice(0, props.items.length);
}, [props.items]);
return props.items.map((item, i) => (
<div
key={i}
ref={el => itemsRef.current[i] = el}
style={{ width: `${(i + 1) * 100}px` }}>
...
</div>
));
}
A ref is initially just { current: null } object. useRef keeps the reference to this object between component renders. current value is primarily intended for component refs but can hold anything.
There should be an array of refs at some point. In case the array length may vary between renders, an array should scale accordingly:
const arrLength = arr.length;
const [elRefs, setElRefs] = React.useState([]);
React.useEffect(() => {
// add or remove refs
setElRefs((elRefs) =>
Array(arrLength)
.fill()
.map((_, i) => elRefs[i] || createRef()),
);
}, [arrLength]);
return (
<div>
{arr.map((el, i) => (
<div ref={elRefs[i]} style={...}>
...
</div>
))}
</div>
);
This piece of code can be optimized by unwrapping useEffect and replacing useState with useRef but it should be noted that doing side effects in render function is generally considered a bad practice:
const arrLength = arr.length;
const elRefs = React.useRef([]);
if (elRefs.current.length !== arrLength) {
// add or remove refs
elRefs.current = Array(arrLength)
.fill()
.map((_, i) => elRefs.current[i] || createRef());
}
return (
<div>
{arr.map((el, i) => (
<div ref={elRefs.current[i]} style={...}>
...
</div>
))}
</div>
);
Update
New React Doc shows a recommended way by using map.
Check the Beta version here (Dec, 2022)
There are two ways
use one ref with multiple current elements
const inputRef = useRef([]);
inputRef.current[idx].focus();
<input
ref={el => inputRef.current[idx] = el}
/>
const {useRef} = React;
const App = () => {
const list = [...Array(8).keys()];
const inputRef = useRef([]);
const handler = idx => e => {
const next = inputRef.current[idx + 1];
if (next) {
next.focus()
}
};
return (
<div className="App">
<div className="input_boxes">
{list.map(x => (
<div>
<input
key={x}
ref={el => inputRef.current[x] = el}
onChange={handler(x)}
type="number"
className="otp_box"
/>
</div>
))}
</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
use an Array of ref
As the above post said, it's not recommended since the official guideline (and the inner lint check) won't allow it to pass.
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders.
However, since it's not our current case, the demo below still works, only not recommended.
const inputRef = list.map(x => useRef(null));
inputRef[idx].current.focus();
<input
ref={inputRef[idx]}
/>
const {useRef} = React;
const App = () => {
const list = [...Array(8).keys()];
const inputRef = list.map(x => useRef(null));
const handler = idx => () => {
const next = inputRef[idx + 1];
if (next) {
next.current.focus();
}
};
return (
<div className="App">
<div className="input_boxes">
{list.map(x => (
<div>
<input
key={x}
ref={inputRef[x]}
onChange={handler(x)}
type="number"
className="otp_box"
/>
</div>
))}
</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
The simplest and most effective way is to not use useRef at all. Just use a callback ref that creates a new array of refs on every render.
function useArrayRef() {
const refs = []
return [refs, el => el && refs.push(el)]
}
Demo
<div id="root"></div>
<script type="text/babel" defer>
const { useEffect, useState } = React
function useArrayRef() {
const refs = []
return [refs, el => el && refs.push(el)]
}
const App = () => {
const [elements, ref] = useArrayRef()
const [third, setThird] = useState(false)
useEffect(() => {
console.log(elements)
}, [third])
return (
<div>
<div ref={ref}>
<button ref={ref} onClick={() => setThird(!third)}>toggle third div</button>
</div>
<div ref={ref}>another div</div>
{ third && <div ref={ref}>third div</div>}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
</script>
<script src="https://unpkg.com/#babel/standalone#7/babel.min.js"></script>
<script src="https://unpkg.com/react#17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.production.min.js"></script>
Note that you shouldn't use useRef in a loop for a simple reason: the order of used hooks does matter!
The documentation says
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)
But consider that it obviously applies to dynamic arrays... but if you're using static arrays (you ALWAYS render the same amount of components) don't worry too much about that, be aware of what you're doing and leverage it 😉
You can use an array(or an object) to keep track of all the refs and use a method to add ref to the array.
NOTE: If you are adding and removing refs you would have to empty the array every render cycle.
import React, { useRef } from "react";
const MyComponent = () => {
// intialize as en empty array
const refs = useRefs([]); // or an {}
// Make it empty at every render cycle as we will get the full list of it at the end of the render cycle
refs.current = []; // or an {}
// since it is an array we need to method to add the refs
const addToRefs = el => {
if (el && !refs.current.includes(el)) {
refs.current.push(el);
}
};
return (
<div className="App">
{[1,2,3,4].map(val => (
<div key={val} ref={addToRefs}>
{val}
</div>
))}
</div>
);
}
working example
https://codesandbox.io/s/serene-hermann-kqpsu
Assuming that your array contains non primitives, you could use a WeakMap as the value of the Ref.
function MyComp(props) {
const itemsRef = React.useRef(new WeakMap())
// access an item's ref using itemsRef.get(someItem)
render (
<ul>
{props.items.map(item => (
<li ref={el => itemsRef.current.set(item, el)}>
{item.label}
</li>
)}
</ul>
)
}
I use the useRef hook to create panels of data that I want to control independently. First I initialize the useRef to store an array:
import React, { useRef } from "react";
const arr = [1, 2, 3];
const refs = useRef([])
When initializing the array we observe that it actually looks like this:
//refs = {current: []}
Then we apply the map function to create the panels using the div tag which we will be referencing, adds the current element to our refs.current array with one button to review:
arr.map((item, index) => {
<div key={index} ref={(element) => {refs.current[index] = element}}>
{item}
<a
href="#"
onClick={(e) => {
e.preventDefault();
onClick(index)
}}
>
Review
</a>
})
Finally a function that receives the index of the pressed button we can control the panel that we want to show
const onClick = (index) => {
console.log(index)
console.log(refs.current[index])
}
Finally the complete code would be like this
import React, { useRef } from "react";
const arr = [1, 2, 3];
const refs = useRef([])
//refs = {current: []}
const onClick = (index) => {
console.log(index)
console.log(refs.current[index])
}
const MyPage = () => {
const content = arr.map((item, index) => {
<div key={index} ref={(element) => {refs.current[index] = element}}>
{item}
<a
href="#"
onClick={(e) => {
e.preventDefault();
onClick(index)
}}
>
Review
</a>
})
return content
}
export default MyPage
It works for me! Hoping that this knowledge will be of use to you.
All other options above are relying on Arrays but it makes things extremely fragile, as elements might be reordered and then we don't keep track of what ref belongs to what element.
React uses the key prop to keep track of items. Therefore if you store your refs by keys there won't be any problem :
const useRefs = () => {
const refs = useRef<Record<string,HTMLElement | null>>({})
const setRefFromKey = (key: string) => (element: HTMLElement | null) => {
refs.current[key] = element;
}
return {refs: refs.current, setRefFromKey};
}
const Comp = ({ items }) => {
const {refs, setRefFromKey} = useRefs()
const refsArr = Object.values(refs) // your array of refs here
return (
<div>
{items.map(item => (
<div key={item.id} ref={setRefFromKey(item.id)}/>
)}
</div>
)
}
Note that React, when unmounting an item, will call the provided function with null, which will set the matching key entry to null in the object, so everything will be up-to-date.
If I understand correctly, useEffect should only be used for side effects, for this reason I chose instead to use useMemo.
const App = props => {
const itemsRef = useMemo(() => Array(props.items.length).fill().map(() => createRef()), [props.items]);
return props.items.map((item, i) => (
<div
key={i}
ref={itemsRef[i]}
style={{ width: `${(i + 1) * 100}px` }}>
...
</div>
));
};
Then if you want to manipulate the items / use side effects you can do something like:
useEffect(() => {
itemsRef.map(e => e.current).forEach((e, i) => { ... });
}, [itemsRef.length])
import React, { useRef } from "react";
export default function App() {
const arr = [1, 2, 3];
const refs = useRef([]);
return (
<div className="App">
{arr.map((item, index) => {
return (
<div
key={index}
ref={(element) => {
refs.current[index] = element;
}}
>
{item}
</div>
);
})}
</div>
);
}
Credits: https://eliaslog.pw/how-to-add-multiple-refs-to-one-useref-hook/
React will re-render an element when its ref changes (referential equality / "triple-equals" check).
Most answers here do not take this into account. Even worse: when the parent renders and re-initializes the ref objects, all children will re-render, even if they are memoized components (React.PureComponent or React.memo)!
The solution below has no unnecessary re-renders, works with dynamic lists and does not even introduce an actual side effect. Accessing an undefined ref is not possible. A ref is initialized upon the first read. After that, it remains referentially stable.
const useGetRef = () => {
const refs = React.useRef({})
return React.useCallback(
(idx) => (refs.current[idx] ??= React.createRef()),
[refs]
)
}
const Foo = ({ items }) => {
const getRef = useGetRef()
return items.map((item, i) => (
<div ref={getRef(i)} key={item.id}>
{/* alternatively, to access refs by id: `getRef(item.id)` */}
{item.title}
</div>
))
}
Caveat: When items shrinks over time, unused ref objects will not be cleaned up. When React unmounts an element, it will correctly set ref[i].current = null, but the "empty" refs will remain.
You can avoid the complexity array refs bring in combination with useEffect by moving the children into a separate component. This has other advantages the main one being readability and making it easier to maintain.
const { useRef, useState, useEffect } = React;
const ListComponent = ({ el }) => {
const elRef = useRef();
const [elWidth, setElWidth] = useState();
useEffect(() => {
setElWidth(elRef.current.offsetWidth);
}, []);
return (
<div ref={elRef} style={{ width: `${el * 100}px` }}>
Width is: {elWidth}
</div>
);
};
const App = () => {
return (
<div>
{[1, 2, 3].map((el, i) => (
<ListComponent key={i} el={el} />
))}
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
We can't use state because we need the ref to be available before the render method is called.
We can't call useRef an arbitrary number of times, but we can call it once:
Assuming arr is a prop with the array of things:
const refs = useRef([]);
// free any refs that we're not using anymore
refs.current = refs.current.slice(0, arr.length);
// initialize any new refs
for (let step = refs.current.length; step < arr.length; step++) {
refs.current[step] = createRef();
}
You can use a father element to get a bounch of children elements.
In my case i was trying to get a bounch of inputs inside my form element then i get the form element and use it to handle with all the inputs.
Somthing like that:
function Foo() {
const fields = useRef<HTMLFormElement>(null);
function handlePopUp(e) {
e.preventDefault();
Array.from(fields.current)
.forEach((input: HTMLInputElement | HTMLTextAreaElement) => {
input.value = '';
});
}
return (
<form onSubmit={(e) => handlePopUp(e)} ref={fields}>
<input
placeholder="Nome"
required
id="name"
type="text"
name="name"
/>
<input
placeholder="E-mail"
required
id="email"
type="email"
name="email"
/>
<input
placeholder="Assunto"
required
id="subject"
type="text"
name="subject"
/>
<textarea
cols={120}
placeholder="Descrição"
required
id="description"
name="description"
/>
<button type="submit" disabled={state.submitting}>enviar</button>
</form>
);
}
We can use an array ref to memoize the ref list:
import { RefObject, useRef } from 'react';
type RefObjects<T> = RefObject<T>[];
function convertLengthToRefs<T>(
length: number,
initialValue: T | null,
): RefObjects<T> {
return Array.from(new Array(length)).map<RefObject<T>>(() => ({
current: initialValue,
}));
}
export function useRefs<T>(length: number, initialValue: T | null = null) {
const refs = useRef<RefObjects<T>>(convertLengthToRefs(length, initialValue));
return refs.current;
}
It is a demo:
const dataList = [1, 2, 3, 4];
const Component: React.FC = () => {
const refs = useRefs<HTMLLIElement>(dataList.length, null);
useEffect(() => {
refs.forEach((item) => {
console.log(item.current?.getBoundingClientRect());
});
}, []);
return (
<ul>
{dataList.map((item, index) => (
<li key={item} ref={refs[index]}>
{item}
</li>
))}
</ul>
);
};
import { createRef } from "react";
const MyComponent = () => {
const arrayOfElements = Array.from({ length: 10 }).map((_, idx) => idx + 1);
const refs = arrayOfElements.map(() => createRef(null));
const onCLick = (index) => {
ref[index]?.current?.click();
};
return (
<div>
<h1>Defaults Elements</h1>
{arrayOfElements.map((element, index) => (
<div key={index} ref={refs[index]}>
Default Elemnt {element}
</div>
))}
<h2>Elements Handlers</h2>
{arrayOfElements.map((_, index) => (
<button key={index} onClick={() => onCLick(index)}>
Element {index + 1} Handler
</button>
))}
</div>
);
};