Strategies for choosing the perfect GIF to showcase in a React JS project

Hey everyone, I'm completely new to working with react JS and I've encountered a problem. I have a task where I need to display GIFs when a button is clicked, but I'm struggling to select a specific GIF. Can anyone provide some guidance on fixing this issue?

If you have any questions, please feel free to ask.

https://i.sstatic.net/fmp0E.png

App.js

I utilized the GIPHY API to show GIFs and Axios for fetching data.

import "./App.css";
import { useEffect, useState } from "react";
import Axios from 'axios';

function App() {

const Api_key="XXX";
const Base_Url = "http://api.giphy.com/v1/gifs/search";

const [searchText,setSearchText] = useState("");
const [searchGif,setSearchGif] = useState("");

const [addText,setAddText] = useState([]);
const [gifs,setGifs] = useState([]);


const postValue = ()=>{

  // Add Text

  const addData = {
    id:Date.now(),
    name:searchText
  }
  console.log(addData);
  setAddText([...addText,addData])
  setSearchText("");

  // Add Gifs
  gifResponse();
 
}

const gifResponse = async()=>{
  const response = await Axios.get(`${Base_Url}?api_key=${Api_key}&q=${searchGif}`)
    //  const res = await response.json();
    setGifs(response.data.data);
   console.log(response.data.data)
 }

  return (
    <div className="App">
      <div className="container">
        <textarea
          type="text"
          className="textarea form-control shadow-none mt-3"
          rows="15"
          cols="45"
          placeholder="Write Something Here..."
          value={searchText}
          onChange={(e)=>setSearchText(e.target.value)}
        />
        <div class="input-group mb-3 mt-2">
          <input
            type="text"
            class="form-control shadow-none inputtext"
            placeholder="Search Gif..."
            aria-label="Recipient's username"
            aria-describedby="basic-addon2"
            value={searchGif}
            onChange={(e)=>setSearchGif(e.target.value)}
          />
          <div class="input-group-append">
            <span class="input-group-text " id="basic-addon2" onClick={postValue}>
              POST & SEARCH
            </span>
          </div>
        </div>
        {
          addText.map((add,index)=>{
            return <h4 key={index}>{add.name}</h4>
          })
        }
        {
          gifs.map((gif)=>{
            return <img src={gif.images.fixed_height.url} />
          })
        }
      </div>
    </div>
  );
}

export default App;

Answer №1

To integrate a gif into your postValue function, simply include the URL of the gif.

Start by setting up a state for the selected gif:

const [chosenGif, setChosenGif] = useState("");

Within your Gif loop, assign an onClick event to designate the selected gif:

 gifs.map((gif, index)=> <img src={gif.images.fixed_height.url} key={"gif-"+index} onClick={() => setChosenGif(gif.images.fixed_height.url)} />)

Note that it's crucial to include a key property when looping through elements.

For the final step, incorporate the selected gif in your postValue function:

const updatedData = {
    id: Date.now(),
    name: searchText,
    gifUrl: chosenGif
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Decoding the enigma of addEventListener in Nuxt: Unveiling the "referenceError: window is not defined" issue

I am currently working on developing a hamburger menu, but I have encountered an error. The error message states: ReferenceError: window is not defined. The issue seems to be within the created section of the code. <script> export default { ...

Navigating a controller variable to access a property of a service

I've been struggling to access a property of a service through a bound controller variable in a template. Controller: app.controller('VictoryController', function($scope, AlertStatisticsService) { $scope.AlertStats = AlertStatisticsSer ...

Why won't my JavaScript addEventListener activate on form submission?

I have a basic question as a beginner in JavaScript. I am facing some challenges with my first task involving JavaScript. I decided to learn JS by creating a TODO List, but I am stuck right at the beginning. The event listener that should respond when the ...

Aligning a single component in the center vertically with the appbar positioned at the top of the screen using Material

As a beginner with material UI, I am facing challenges in centering a component both horizontally and vertically on my screen while including an AppBar for navigation at the top. While I have come across solutions like this example using a grid system, i ...

Display notification only on certain days

I'm trying to create an alert that only pops up on specific days, but I can't seem to figure it out $(document).ready(function () { $days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday&a ...

Guide on securely presenting an HTTP-only cookie as a bearer token, without the use of Angular.JS

Can a JWT be securely stored as an HTTP-only cookie and also used as a bearer token without relying on Angular.JS? I believe this could be achievable, as Angular.JS offers similar features (although I'm not sure if they use an HTTP-only cookie to sto ...

What is the best way to display the identical HTML page for both online and offline applications?

I am facing a challenge with my application, as I need to ensure that it can also be accessed offline. While I can easily create dynamic content on the client side using Javascript and JQuery instead of relying on server-side processing, I am struggling wi ...

Using a combination of AND and OR in XPATH

Recently, I encountered the following HTML code: <div><h6>abc/h6><p>date</p></div> Using Selenium, I managed to locate this element based on text. However, the issue arises when <h6> can contain various words like "d ...

Resolving problems with image dimensions in Angularjs and ionic framework

I'm attempting to achieve a design where the first image occupies 50% of the screen's height and 100% of its width, while the second image does the same. Please refer to the image below: https://i.sstatic.net/nwmRP.jpg ...

Error: The function eleves.map is not supported in React/Spring-boot, causing a failure to display the @ManyToOne relation

Currently, I am encountering an issue with displaying 2 entities in a Many to One relationship. When the data is saved in the student entity with the level entity left as null, everything works smoothly because the response is an object. However, when a s ...

"Implementing Diagonal Gradients for Web Dev in Internet Explorer

Is there a way to create a diagonal gradient background in Internet Explorer? I have researched on this and found that IE only supports horizontal and vertical gradients. Can the gradient in IE be displayed diagonally like in Firefox? ...

Experiencing difficulties launching my Server.JS due to a listening error

Hey there, I'm struggling to get my server.js up and running. Whenever I try to run node on it, I keep getting the error message "listening on *:3000". Below is the code for my server.js: var app = require('express')(); var http = require(&a ...

Having trouble pinpointing the source files that are loading .js in the <head> section of my Magento website

My console is showing me three 404 errors related to missing .js files in the head section of my website. Even though I don't actually need these files, I want to stop receiving the 404 errors as they are affecting my analytics and SEO. The files caus ...

Implementing the useFormik hook for user authentication

Is anyone familiar with the useFormik hook? I am trying to validate a username and password on the server using the handleLogin(username, password) method. This is the code snippet I am currently working with: const LoginForm = withFormik({ mapPropsToV ...

Remove and modify an li element that has been dynamically generated within a ul list

Currently, I am facing an issue in my code. I am dynamically creating li elements by taking input from an input box and then appending the data within li tags using jQuery. However, after adding the li element, I have included a delete button. The problem ...

Store and Persist Data for a Model in MongoDB

Currently working through the MongoDB and Mongoose section on FreeCodeCamp. The challenge involves creating a document instance using the Person constructor previously built. The object passed to the constructor should have fields for name, age, and favor ...

Tips for refining search outcomes from web scraping with Google App Script

My objective is to scrape data from the website : I am specifically interested in extracting the SP500 PE number, which currently stands at 39.57 (at the time of writing). I require this number to be formatted as 39,57, rather than 39.57. This is my curr ...

The primary tab's background color in a Shiny app

I had this question deleted previously while I was in the process of refining it. Is there a way to customize the background color of the active tab in a Shiny app? library(shiny) ui <- fluidPage( tags$head( tags$style(HTML(css)) ), tabsetP ...

Adhesive Bottom Navigation, Top Banner, and Full-Height Page Content

Trying to create a header, sticky footer, and content section with 100% height, but facing issues with the middle height. Below is the code and jsfiddles provided. Using HTML 4.0 strict in IE7 without the option to change. jsfiddle without 100% height: ht ...

Using isomorphic-fetch with Sinon spy

Creating a straightforward thunk action to retrieve data from an API was my task. Here is the code snippet: import fetch from 'isomorphic-fetch'; function json(response) { return response.json(); } /** * Retrieves books from the server */ ...