I have an Ag Grid that is made with Vanilla Javascript. I am adding some custom cell renderers, and I wanted to use a React cell renderer.
I know Ag Grid has native support for React cells if the grid is using React, but is it possible to have a React cell when the grid is Vanilla Javascript?
CodePudding user response:
Yes it is possible, but it is highly recommended to convert your app whole to React if you're going to be doing this.
With that said, you can do by rendering your component into a virtual DOM element. This is likely the way ag-grid React is implemented under the hood (at least to some degree).
JSFiddle: https://jsfiddle.net/p2oa5ch0/1/
function MyComponent({data}) {
return React.createElement("span", null, `Rendered Make: ${data.make}`)
}
var columnDefs = [
{headerName: "Make", field: "make", cellRenderer: ({data}) => {
const el = document.createElement("div");
const root = ReactDOM.createRoot(el)
root.render(React.createElement(MyComponent, { data }))
return el;
}},
{headerName: "Model", field: "model"},
{headerName: "Price", field: "price"}
];
// specify the data
var rowData = [
{make: "Toyota", model: "Celica", price: 35000},
{make: "Ford", model: "Mondeo", price: 32000},
{make: "Porsche", model: "Boxter", price: 72000}
];
// let the grid know which columns and what data to use
var gridOptions = {
columnDefs: columnDefs,
rowData: rowData
};
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
});
Note: I don't know how to make JSX work in JSFiddle, but this approach will work with JSX instead of React.createElement
if your toolchain is set up for it.
As opposed to rendering the component to a string and displaying it, this will also work with dynamic state: https://jsfiddle.net/z6wtd5uj/