Integrando Ignite UI for React com Next.js
Explore a integração perfeita do Ignite UI for React em seu projeto Next.js. Este tópico foi criado para ajudar os desenvolvedores a aproveitar ao máximo os componentes Infragistics React e, ao mesmo tempo, aproveitar os recursos do Next.js para criar aplicativos de pilha completa robustos e de alto desempenho.
Prerequisites
- Instale o NodeJS.
- Instale o Visual Studio Code.
Creating New Next.js Project
Com os pré-requisitos acima instalados, podemos criar um novo aplicativo Next.js.
1 - Abra o VS Code, selecione o menu Terminal e depois a opção Novo Terminal.
2 - Digite os seguintes comandos na janela do terminal:
npx create-next-app@latest MyAppName
cd MyAppName
Updating Existing Next.js App
Se você quiser usar Ignite UI for React em um projeto Next.js existente (um que você tenha antes). Nós temos você coberto! Tudo o que você precisa fazer é executar estes comandos:
npm install --save igniteui-react
npm install --save igniteui-react-charts igniteui-react-core
npm install --save igniteui-react-excel igniteui-react-core
npm install --save igniteui-react-gauges igniteui-react-core
npm install --save igniteui-react-grids igniteui-react-core
npm install --save igniteui-react-maps igniteui-react-core
npm install --save igniteui-react-spreadsheet igniteui-react-core
Ou
yarn add igniteui-react-charts igniteui-react-core
yarn add igniteui-react-excel igniteui-react-core
yarn add igniteui-react-gauges igniteui-react-core
yarn add igniteui-react-grids igniteui-react-core
yarn add igniteui-react-maps igniteui-react-core
yarn add igniteui-react-spreadsheet igniteui-react-core
Isso instalará automaticamente os pacotes do Ignite UI for React, juntamente com todas as suas dependências, importações de fontes e referências de estilos para o projeto existente.
Importing Component Modules
Primeiro, temos que importar os módulos necessários dos componentes que queremos usar. Vamos em frente e faremos isso para o componente GeographicMap.
"use client"
import { IgrGeographicMapModule, IgrGeographicMap } from 'igniteui-react-maps';
import { IgrDataChartInteractivityModule } from 'igniteui-react-charts';
IgrGeographicMapModule.register();
IgrDataChartInteractivityModule.register();
[!Note] It's important to note that Ignite UI for React components are using client-only features like state and browser events. Infragistics' components will work as expected within Client Next.js Components since they have the "use client" directive, but they won't work within Server Components.
Using Components
Agora estamos prontos para usar o componente de mapa Ignite UI for React em nosso componente Next.js! Vamos em frente e defini-lo:
function App() {
return (
<div style={{ height: "100%", width: "100%" }}>
<IgrGeographicMap
width="800px"
height="500px"
zoomable="true" />
</div>
);
}
Running Application
Finalmente, podemos executar nosso novo aplicativo usando um dos seguintes comandos:
npm run dev
Depois de executar esse comando, seu projeto será construído e servido localmente em seu computador. Ele será aberto automaticamente em seu navegador padrão e você poderá usar Ignite UI for React componentes em seu projeto.
O resultado final deve ser semelhante a esta captura de tela:

Using React in Next.js Server Components
Como mencionado anteriormente, a maioria dos componentes do React depende de eventos de estado e navegador, tornando-os incompatíveis com o uso direto nos componentes do servidor. No entanto, se você achar necessário usá-los dessa maneira, Infragistics componentes ' podem ser agrupados em seus respectivos componentes do cliente.
'use client'
import { IgrGeographicMap } from 'igniteui-react-maps';
IgrGeographicMapModule.register();
export default IgrGeographicMap;
Em seguida, em um componente do servidor Next.js, o IgrGeographicMap pode ser usado diretamente:
import IgrGeographicMap from './wrapped-geographic-map';
function App() {
return (
<div style={{ height: "100%", width: "100%" }}>
<IgrGeographicMap
width="800px"
height="500px"
zoomable="true" />
</div>
);
}
[!Note] The majority of Ignite UI for React components may remain unwrapped as they are expected to be utilized within other Client Components. Therefore, there is no need to wrap all Infragistics' components.
Dynamic import of Ignite UI for React components
O aprimoramento do desempenho de carregamento inicial de um aplicativo é facilitado pelo carregamento lento, que reduz a quantidade necessária de JavaScript para renderizar uma rota. Ele permite que você adie o carregamento das bibliotecas importadas e as inclua apenas no pacote configurável do cliente quando necessário. Usando next/dynamic
você pode implementar o carregamento lento:
"use client";
import "igniteui-webcomponents/themes/light/bootstrap.css";
import dynamic from "next/dynamic";
export default function DynamicButtonComponent() {
const IgButton = dynamic(
async () => {
const { IgrButton, IgrButtonModule } = await import("igniteui-react");
IgrButtonModule.register();
return IgrButton;
}
);
return (
<IgButton variant="contained">
<span key="title">Click me</span>
</IgButton>
);
}
No entanto, se um componente mais complexo for usado como o IgrGrid, que normalmente contém componentes filho, é essencial não importar dinamicamente cada componente filho. O componente deve ser usado assim:
"use client";
import dynamic from "next/dynamic";
import CustomersDataLocal from "./CustomersDataLocal.json";
import "igniteui-react-grids/grids/combined";
import "igniteui-react-grids/grids/themes/light/bootstrap.css";
export default function GridDynamicComponent() {
const IgnGrid = dynamic(
async () => {
const {
IgrGrid,
IgrGridModule,
IgrColumn,
IgrGridToolbar,
IgrGridToolbarTitle,
IgrGridToolbarActions,
IgrGridToolbarPinning,
} = await import("igniteui-react-grids");
IgrGridModule.register();
const IgGrid = ({ ...props }) => {
return (
<IgrGrid {...props}>
<IgrGridToolbar>
<IgrGridToolbarTitle></IgrGridToolbarTitle>
<IgrGridToolbarActions>
<IgrGridToolbarPinning></IgrGridToolbarPinning>
</IgrGridToolbarActions>
</IgrGridToolbar>
<IgrColumn field="ID" header="ID" hidden="true"></IgrColumn>
<IgrColumn
field="CompanyName"
header="Company Name"
width="300px"
></IgrColumn>
<IgrColumn
field="ContactName"
header="Contact Name"
width="200px"
pinned="true"
></IgrColumn>
<IgrColumn
field="ContactTitle"
header="Contact Title"
width="200px"
pinned="true"
></IgrColumn>
<IgrColumn
field="Address"
header="Address"
width="300px"
></IgrColumn>
<IgrColumn field="City" header="City" width="120px"></IgrColumn>
<IgrColumn field="Region" header="Region" width="120px"></IgrColumn>
<IgrColumn
field="PostalCode"
header="Postal Code"
width="150px"
></IgrColumn>
<IgrColumn field="Phone" header="Phone" width="150px"></IgrColumn>
<IgrColumn field="Fax" header="Fax" width="150px"></IgrColumn>
</IgrGrid>
);
};
return IgGrid;
}
);
return <IgnGrid data={CustomersDataLocal}></IgnGrid>;
}
[!Note] Implementing lazy loading for components can enhance performance, but it is advisable to use it exclusively when the components are not immediately visible on the page.
Limitations
- Se o seu projeto Next.js estiver usando o roteamento de página, você deverá transcompilar os pacotes Ignite UI for React usando as
next.config.js
opções. Sua configuração deve conter o seguinte:
const nextConfig = {
transpilePackages: ['igniteui-react'],
experimental: {
esmExternals: "loose",
}
}
Additional Resources
Nossa comunidade é ativa e sempre acolhedora para novas ideias.