Rating component React

How to implement a rating component in React

Lyket is the ultimate tool to add rating components to any React app! Lyket library allows a great deal of customization with just a few lines of code and it's compatible with all React frameworks like NextJS, Gatsby, create-react-app.

import { Provider, RateButton } from "@lyket/react";

<Provider apiKey="acc0dbccce8e557db5ebbe6d605aaa">
  <RateButton
    namespace="testing-react"
    id="everybody-rate-now"
  />
</Provider>

Your rating

Average rating

If you want to find out how to use the React library in detail you came to the right place. If you prefer to learn with examples and ready-made snippets to copy and paste, you can visit:

How Lyket rating component works

All Lyket buttons share these basic behaviors and features:

  • As soon as a button component is mounted, a fetch request is made to retrieve info on the button that identifies with the ID and namespace that you provided. If no button is found, a new one will be created using the ID/namespace identifier.

  • Notice that the server will create a new button for every different and unique identifier, so if you change ID or namespace or type the new button won’t inherit the votes.

  • Every time a visitor interacts with a button, the button counter will update and Lyket will flag that the visitor has voted. Lyket uses an unique random ID stored in the visitor's browser localStorage to identify the visitor, with no need to signup or to use any third party service. To disable the session ID, and therefore use only the IP address to identify a user, set the disableSessionId prop to true in the Provider component.

  • Lyket enforces a maximum number of sessions IDs per IPaddress to avoid receiving too many requests or DDoS attacks. The default is 3 sessions per IP. You can change this number by logging into your private area and edit the user settings.

  • In the user settings you can also specify from which domains Lyket should accept requests using your personal API key. If left empty Lyket will accept requests coming from all domains.

Install Lyket

Well, Let's get started! To install the component run

yarn add @lyket/react

or

npm install @lyket/react
Add Lyket to your app

Add the Provider component top-level and configure it using your personal public API key that you can get after registering to Lyket

import { Provider } from '@lyket/react';
								
ReactDOM.render(
	<Provider apiKey="[YOUR-API-KEY]">
		<App />
	</Provider>,
	document.getElementById('root')
);
Required props
  • apiKey: string - You can get your public API key by registering on Lyket.
Optional props
  • theme: Record<'colors' | 'fonts' , Record<string, string>> - Allows you to change the default buttons colors and fonts. It doesn't apply to all templates. Read more about it in the Styling buttons section at the end of this document.

  • recaptchaSiteKey: string - If you enabled reCAPTCHA in the private area's user settings, you need to provide your reCAPTCHA public key, otherwise your buttons will result as unauthorized. Read more in the reCAPTCHA section at the end of this document.

  • disableSessionId: boolean Default: false - If set to true Lyket won't store a unique session ID for your visitors making them anonymous. Lyket will then discriminate visitors (to tell if they already liked a button or not) only based on the IP address. Disabling the session ID can be useful if you don't want Lyket to result in your cookie detection software.

Configuring the rating component

Once you configured the Provider you can add rating components anywhere in your app.

Lyket rating component behaves like Trip Advisor rating component.Users can only vote once and a subsequent click on the same component from the same visitor will remove the user's vote.

Rating components have two interfaces. Given the same button, ie. with same id-namespace combination, you may want to show two types of information: the average rating for that button, and an interface in which the user can click to leave their rating. You can select which interface you want to show, with the attribute showRating

import { RateButton } from '@lyket/react';

export Restaurant = () => {
  return (
    <div>
      <h1>My Restaurant</h1>
		<p>Average ratings for My Restaurant</p>
      <RateButton
        id="my-restaurant"
        namespace="restaurants"
				showRating="average"
      />
		<p>Rate My Restaurant</p>
      <RateButton
        id="my-restaurant"
        namespace="restaurants"
				showRating="user"
      />
      {content}
    </div>
    );
  };
Average rating:

Click to rate! β†’

Required props
  • id: string - The API uses the ID to find a button. It should be unique for namespace. It accepts an alphanumeric string with maximum 50 characters.
  • showRating: "user" | "average" - You need to specify whether you want to display the average users rating or the current user rating. Only the user rating can be clicked.
Optional props
  • namespace: string - Giving a namespace is useful to keep buttons organised, and can be used to fetch statistics. Check the API docs for more information.

  • hideCounterIfLessThan: number - You may want to hide the counter if you are not getting enough feedback. Specify the number of votes/claps/likes you want to receive before showing the counter.

  • totalReviewsLabel: string - Default is "reviews". Customize the label that shows after the average rating total number of ratings

  • component: React.ReactNode - If this prop is not provided you will see the Star template. To change the aspect of your buttons you can either choose one of the ready-made templates or a custom component and pass it through the component attribute.

  • onLoad: (buttonData: UpdownButtonData | ClapButtonData | RateButtonData) => void - This function gets called when the button has finished loading. buttonData has different format depending on the button type.

  • onPress: (buttonData: RateButtonData) => void - This function gets called whenever a Press action is triggered.

React rate component Templates

Lyket provides a set of out-of-the-box templates. You can see all the available templates in the templates page

By default, ie. if you don't specify any template or custom component, Lyket will show the Star Template.

  • Star (default) - supports custom theme
  • Heart: Heart style - supports custom theme

Import templates directly from the button. Here is an example of using the Heart template on a RateButton.

import { RateButton } from '@lyket/react';

export StandingOvation = () => {
  return (
    <>
      <h4 id="How much do you like pizza?">Do you like pizza?</h4>
      <RateButton
        id="do-you-like-pizza"
        component={RateButton.templates.Heart}
      />
    </>
  );
};

Custom rate component

You may want to give a different flavour to your rating component, for example using your company logo as the icon. You can do that by creating your own custom button!

These are the available props:

  • handlePressUp: (buttonData: ClapButtonData) => void
  • totalVotes: number
  • averageRating: number
  • userRating: number
  • isLoading: boolean
  • isCounterVisible: boolean
import { RateButton } from '@lyket/react';

<RateButton
	id="custom-button"
	namespace="pizza"
	onLoad={onLoad}
	onPress={onPress}
>
	{({
		handlePress,
		averageRating,
		userRating,
		isLoading,
		totalVotes,
	}) => (
		<>
			{Array.from(Array(5).keys()).map((index) => {
				if (userRating > index) {
					return (
						<button
							key={index}
							onClick={() => handlePress(index + 1)}
							disabled={isLoading}
						>
							πŸ•
						</button>
					);
				} else {
					return (
						<button
							onClick={() => handlePress(index + 1)}
							disabled={isLoading}
						>
							πŸ’”
						</button>
					);
				}
			})}
			<div>Your rating: {userRating}</div>
			<div>Average rating: {averageRating} stars out of 5</div>
			<div>Total votes: {totalVotes}</div>
		</>
	)}
</RateButton>
Your rating:
Average rating: 0 stars out of 5
Total votes: 0

Style your rating component templates

Resizing

All button templates can be resized by wrapping them in a container and changing the font-size.

Apply your color scheme and fonts

Lyket uses the theme-ui library, allowing you to provide your own color palette to the buttons through the theme prop in the provider. Colors support rgba, hex, and color names.

import { Provider, Rating } from "@lyket/react";

<Provider
  apiKey="undefined"
  theme={{
    colors: {
			primary: "#ffaa02",
			icon: "lightgrey",
			text: "purple",
    }
  }}
>
	<span className="try">Average rating: </span>
	<RateButton
		namespace="cooking-book"
		id="my-ramen-recipe"
		showRating="average"
	/>
	<span className="try">Click to rate! β†’</span>
	<RateButton
		namespace="cooking-book"
		id="my-ramen-recipe"
		showRating="user"
	/>
</Provider>
  
Average rating:
Click to rate! β†’
Button colors
  • primary - Changes the color of the icon that shows the rating.
  • icon - Changes the color of the inactive icon.
  • text - Changes the counter text color.
  • highlight - Changes the animation color.
Button fonts
  • body - Changes counter font.

These are the default values:

const defaultTheme = {
	colors: {
		primary: '#22c1c3',
		secondary: '#ff00c3',
		background: 'transparent',
		text: '#292929',
		highlight: '#e095ed',
		icon: '#292929',
	},
	fonts: {
		body: 'inherit',
	},
};

reCAPTCHA

Lyket is integrated with Google reCAPTCHA V3 to handle malicious use without interrupting human users. To enable it you need to provide your Google reCAPTCHA secret key in the user settings in the private area and add your recaptcha site key through the recaptchaSiteKey prop in the Provider. The key will be encrypted.

In this way each time a user interacts with a button an "invisible" reCAPTCHA check will be performed, keeping your website safe.

Be aware that if you only set reCAPTCHA secret key in the user settings while not passing the reCAPTCHA site key in your Provider, the buttons won't work.