Home > Blockchain >  How to hide the settings div after receving an input from the user ? in a React app
How to hide the settings div after receving an input from the user ? in a React app

Time:04-08

I have a simple Quiz app that fetches the questions from an API (https://opentdb.com/api.php?amount=100), filters them by difficulty, and renders the questions in the 'Questions' component. I want to hide the settings after filtering - when the questions are shown.

This is my code:

import React, { useEffect, useState } from "react";

import Questions from "./Questions";

const Welcome = () => {
  /*Fetch questions*/
  const questionsAPI = "https://opentdb.com/api.php?amount=100";
  const [questionsFromAPI, setQuestionsFromAPI] = useState([]);
  const [difficultyValue, setDifficulty] = useState("");
  const [filteredQ, setFilteredQ] = useState([]);

  const handleDifficultyChange = (event) => {
     setDifficulty(event.target.value);
   };

  const handleSearchReset = () => {
     setDifficulty("");
   };

  const fetchData = () => {
     return fetch(questionsAPI)
       .then((response) => response.json())
       .then((data) => setQuestionsFromAPI(data.results));
  };

   useEffect(() => {
      fetchData();
   }, []);

   useEffect(() => {
      setFilteredQ(
       questionsFromAPI.filter((q) => q.difficulty === difficultyValue)
      );
    }, [questionsFromAPI, difficultyValue]);

   return (
     <div>
       <h1>QUIZ</h1>
      
       **<div classname="setting">
        <h1>Search Posts</h1>
        <br />
        <p>difficulty</p>
        <input
          type="string"
          min={"difficulty"}
          value={difficultyValue}
          onChange={handleDifficultyChange}
        />
        <br />
        <button classname="button" type="button" onClick={handleSearchReset}>
          Reset Search
        </button>
        </div>**
     {filteredQ.length > 0 ? (
      <div>
          <Questions questionsAPI={filteredQ}></Questions>
      </div>
      ) : (
      <br></br>
     )}
   </div>
  );
};

export default Welcome;

CodePudding user response:

In React elements have the attribute hidden, you can use that to hide your settings div. For example by using a hook:

const [isHidden, hideSettings] = useState(false)

And to the settings div add the following

<div hidden={isHidden} classname="setting">

and use hideSettings(true) after filtering

  • Related