In this tutorial, we’ll make a meme generator using ReactJS. In the meme generator, we have two text fields in which we enter the first text and last text. After writing the text when we click the Gen button, it creates a meme with an image and the text written on it.
In this React app, we have only one component: MemeGenerator. MemeGenerator contains a render method that returns a controlled form, the form contains two input fields and one Gen button. When the MemeGenerator component gets rendered on the screen, the componentDidMount() method gets activated and makes an API call, and stores the data received in an array. When the user fills the input field and clicks the Gen button, the form gets submitted, and a random image URL is assigned to the randomImg state variable. The image is shown on the screen along with the text.
Prerequisite: The pre-requisites for this project are:
- Functional and Class Components
- React AJAX and API
Getting Started with React: Our React app contains two components, the App component, and MemeGenerator component.
App.js: App component renders single MemeGenerator component.
MemeGenerator.js: The only component in our App is a MemeGenerator component. It contains four state variables and initially, all of them are set to empty string or empty array. When the component gets mounted on the screen, an API call is made and the data received is converted into JSON and stored in the state variable allMemeImgs[ ]. The MemeGenerator component renders a controlled form to the screen and when the user types the input, the handleChange method gets called, and the state variables topText and bottomText store the text typed by the user. When the user clicks the Gen button, handleSubmit method gets called and a random image URL is stored in randomImg variable. When the randomImg gets the value, the meme is shown to the screen.
Below is the complete code of our MemeGenerator component.
App.css: How to make the topText and lastText get aligned as per the image. The following CSS can be used to make the text aligned
Output: Our app is now complete and working. Below is the App working perfectly.