Skip to content
Related Articles

Related Articles

Create a meme generator by using ReactJS
  • Last Updated : 27 Apr, 2021

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:

  • React
  • Functional and Class Components
  • React AJAX and API
  • ES6 

Getting Started with React: Our React app contains two components, the App component, and MemeGenerator component.

Index.js:



  •  

Javascript




import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
 
ReactDOM.render(<App />, document.getElementById('root'))
  •  
     

App.js: App component renders single MemeGenerator component.

  •  

Javascript




import React from 'react';
import MemeGenerator from './MemeGenerator'
 
function App() {
    return (
        <div className="App">
            <MemeGenerator />
        </div>
    );
}
 
export default App;
  •  
     

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.

  •  

Javascript




// Import React (Mandatory Step).
import React from "react";
 
// MemeGenerator component to generate a meme
class MemeGenerator extends React.Component {
  state = {
    topText: "",
    bottomText: "",
    allMemeImgs: [],
    randomImg: ""
  };
 
  // componentDidMount() method to fetch
  // images from the API
  componentDidMount() {
     
    // Fetching data from the API
      // Converting the promise recieved into JSON
      .then(response => response.json())
      .then(content =>
          // Updating state variables
        this.setState({
          allMemeImgs: content.data.memes
        })
      );
  }
 
  // Method to change the value of input fields
  handleChange = event => {
    // Destructuring the event. target object
    const { name, value } = event.target;
     
    // Updating the state variable
    this.setState({
      [name]: value
    });
  };
 
  // Method to submit from and create meme
  handleSubmit = event => {
    event.preventDefault();
    const { allMemeImgs } = this.state;
    const rand =
      allMemeImgs[Math.floor(Math.random()
      * allMemeImgs.length)].url;
    this.setState({
      randomImg: rand
    });
  };
 
  render() {
    return (
      <div>
        // Controlled form
        <form className="meme-form" onSubmit={this.handleSubmit}>
          // Input field to get First text
          <input
            placeholder="Enter Text"
            type="text"
            value={this.state.topText}
            name="topText"
            onChange={this.handleChange}
          />
          // Input field to get Lsst text
          <input
            placeholder="Enter Text"
            type="text"
            value={this.state.bottomText}
            name="bottomText"
            onChange={this.handleChange}
          />
          // Button to generate meme
          <button>Generate</button>
        </form>
 
        <br />
        <div className="meme">
          // Only show the below elements when the image is ready to be displayed
          {this.state.randomImg === "" ? "" :
            <img src={this.state.randomImg} alt="meme" />}
          {this.state.randomImg === "" ? "" :
            <h2 className="top">{this.state.topText}</h2>}
          {this.state.randomImg === "" ? "" :
            <h2 className="bottom">{this.state.bottomText}</h2>}
        </div>
      </div>
    );
  }
}
 
export default MemeGenerator;
  •  
     

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

  •  

CSS




.meme {
  position: relative;
  width: 59%;
  margin: auto;
}
 
.meme > img {
  width: 100%;
}
 
.meme > h2 {
  position: absolute;
  width: 80%;
  text-align: center;
  left: 50%;
  transform: translateX(-50%);
  margin: 15px 0;
  padding: 0 5px;
  font-family: impact, sans-serif;
  font-size: 1em;
  text-transform: uppercase;
  color: white;
  letter-spacing: 1px;
  text-shadow: 2px 2px 0 #000;
}
 
.meme > .bottom {
  bottom: 0;
}
 
.meme > .top {
  top: 0;
}
 
form {
  padding-top: 25px;
  text-align: center;
}
  •  
     

Output: Our app is now complete and working.  Below is the App working perfectly.

My Personal Notes arrow_drop_up
Recommended Articles
Page :