Walkthrough: Creating widget components using the CLI
This walkthrough is the part two of the Developing the UI walkthrough series.
As part of a Sitecore Discover implementation, you need to create and add widget components to your React application.
This walkthrough describes how to create a widget component with Discover UI components CLI.You need to repeat this walkthrough for every widget in your project.
Alternatively, you can create widget components by manually copying and pasting code from the UI reference site.
This walkthrough describes how to:
-
Install the Discover UI Components CLI.
-
Create a widget component with the UI Components CLI.
-
Edit the widget component code to match design.
-
Edit the styles of a styled widget component
-
Style widget components with a theme.
Install the Discover UI Components CLI
To install the UI Components CLI:
-
In the terminal of your IDE, run the following.
RequestResponsenpx install --save-dev @sitecore-discover/cli -
In a file called
.sc-discover-settings.json, add the location for widget components as shown in the following code block.RequestResponse{ "components-path": "src-test/components" }
Create a widget component with the Discover UI Components CLI.
To create a widget component with Discover UI Components CLI:
-
In the root of your project or in the folder where you have
.sc-discover-settings.json, run the following in the terminal:RequestResponsenpx sc-discover new-widget -
To create a widget component in your desired location, provide answers to select a widget template in the displayed prompts.
NoteThe CLI generates an
index.jsorindex.tsfile based on your language choice.If you choose a styled template, the CLI also generates a
styled.jsorstyled.tsfile.
You can style widget components with theme variables, using styled widget components or by applying custom style in the components.
Edit the widget component code to match design
The widget component in the index.js or index.ts file is based on default product and category entities. They might have more or less attributes than those in your system.
To edit the widget component code to match your design:
-
Open the
index.jsorindex.tsfile. -
To match your requirements for the widget and to reflect attributes included in the results fetched by the JS SDK, edit the React code.
-
Save file.
Make sure all attributes used in a widget component have been defined in the CEC and are marked to return in the API.
Invalid entity attributes can throw runtime errors.
Edit the styles of a styled widget component
If the CLI did not generate a styled.js or styled.ts file, skip the following procedure.
To edit the styles of a styled widget component to match the design:
-
In the
styled.jsorstyled.tsfile, edit the styles.
Style widget components with a theme
Theming an application with CSS variables is the fastest way to style your components. You can use the default theme or a custom theme.