The Score Component for our Quiz will render the data that we are retrieving through REST API. We will create a new React Component
Score and add it to our
Up until now, we have created three React Components:
Answer. The last component that we need is
Score so we can show the results of our Quiz.
The Score Component
Let’s follow the same approach we did in the last tutorial where we have built Question and Answer Components. Create an empty
Score.js file inside the
components folder and then add this code inside of the file:
Score Component will receive a property
score. This property will be an object that contains all the data that we receive from our REST API route which we have defined in the previous tutorial on CPT and REST API Routes.
We will display the percentage and also the score and the maximum score that can be achieved.
Adding Score to Quiz Component
To include the
Score Component in our
Quiz Component, we need to import it from the
components folder. Open our
Quiz.js and do the following changes.
We also need to add our
Score Component in our rendering method so we can render our score.
We are passing the property
score and the value is the score from our
state. We are passing only the first item in our score array. I have decided to define the
state as an array so I can use
this.score.length. But, this could be done differently and I invite you to do so.
Populating the State with Score
In the tutorial on creating the Quiz Component, we have defined the method
getScore. Up until now, that method was an empty method. It did not do anything else then writing some text in the
Update the code for that method to this:
This part required me to do some research because, by default,
fetch is sending
JSON. To send a
POST as if it was sent by a regular form, I had to build the whole
body as a querystring. This was done by going through all the given answers and their question IDs.
Now, when sending the data, our REST API endpoint will work without any changes needed. If we did not do that, we would need to change how we process the
POST requests on that endpoint.
Styling the Quiz
In this tutorial, I have replaced the
App class to
Quiz inside the
Quiz Component. You’re welcome to style the quiz as you want. I’ve just define a few simple CSS rules inside of
Building for Production
Locate yourself, through the Terminal (Command Prompt), inside of
inc/react-wp and type
npm run build. You will see a folder
build populated with a
This can now be used in production.
If you’ve followed all the tutorials on creating the Quiz with React and WP Rest API, you should have a working Quiz.
In my opinion, this was a nice example of how you can use React to build an App which can run anywhere and still have a connection to WordPress. By separating all the various parts into Components, we have kept our code clean and easily maintainable.
Have you tried building other Apps connected to WordPress? Please share your experience with us in the comments below!