I have a component that needs to render an array of divs, the array should add another div after a certain function outside the component is triggered, the function is outside the component because it needs to be exported.
The problem is that if I create the array as a state in the component I can’t set the state in the external function because it is not declared there.
How can I render and update such an array?
const codeContainer = document.querySelector('.codeContainer');
export function DragHandler() {
codeContainer.addEventListener('dragover', function (e) {
e.preventDefault();
});
codeContainer.addEventListener('drop', function (e) {
//a lot of stuff
//new variable containing a div element created here
});
};
const CodePageMain = () => {
return (
<div className='codeContainer'>
//a lot of stuff
//need an array here with a new div variable every time DragHandler() is called
</div>
)
}
export default CodePageMain
I tried creating a state inside the component and passing a function to the SetState that only returns the new div from the function and sets the state inside the component instead of inside the function but I didn’t manage to do it.
2
Answers
You can pass the array as an argument to the external function. In case you need both the function and the array (or the result of the function acting on the array) to be exported, you need to use global state.
The parent could send a function that accepts an item to the child, then adds it to the collection/array. This allows the child to invoke the function with a given item without knowing any implementation details. It does not know how, or to what collection the item is added.
Here is an example, using a drag/drop scenario:
This example is quite a bit different from the code you provided in your question. Generally speaking you try to avoid
addEventListener()
calls when working with React. Most scenarios can be handled with theonEventName={}
props that React provides.I don’t know if this answers your question in full, but I hope you can get some inspiration from this example.
This is also called lifting state up.