Moving External Library From Class-based To Functional Component In React
I'm using the JExcel javascript library with React. The documentation outlines the approach with Components, but makes use of ReactDOM.findDOMNode() which I believe has been deprec
Solution 1:
Okay, with help from Paul @ JExcel here's the trick to get it to work.
importReact, { useRef, useState, useEffect } from'react'import jexcel from'jexcel-pro'exportdefaultfunctionMyGrid(props) {
const { options } = props
const sheetRef = useRef(null)
const [mySheet, setMySheet] = useState(null)
useEffect(() => {
// here's the magic...if (!sheetRef.current.innerHTML && options.data.length > 0) {
setMySheet( jexcel(sheetRef.current, options))
}
// clean-up functionreturnfunctionremoveSheet() {
sheetRef.current.remove();
}
}, [options])
functionaddRow() {
mySheet.insertRow()
}
return (
<div><divref={sheetRef} /><br /><inputtype="button"value="Add new row"onClick={() => addRow()} />
</div>
)
}
To prevent multiple calls to the external library (jexcel in this case) the trick is to check that (a) the params have been passed into the component, i.e. in this case options.data.length > 0
, and (b) that we only call the external library the first time we have those params, i.e. !sheetRef.current.innerHTML
- if the sheetRef
element has no innerHTML, then it hasn't be initiated, so it must be the first time around. Therefore, the call to setMySheet
only happens once, and only when all the properties have been passed in.
Here's a Sandbox showing it in action.
Post a Comment for "Moving External Library From Class-based To Functional Component In React"