Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i render the data value in a h1 element?

How can i render the data value in a h1 element? i have created a simple function its work is to just console random meme name and that function works fine but i want that that random name which iam consoling display in a h1 element in my web page so how can i do that? i want that when i click the button that random name display in my web page in a h1 element not in console

import React from 'react'
import Card from './Card'
import memesData from './memesData';
import './MainContent.css';

function MainContent() {



   function getMemeImage() {

      const memesArray = memesData.data.memes
      const randomNumber = Math.floor(Math.random() * memesArray.length)
      const n = memesArray[randomNumber].name
      console.log(n)
   }

   return (
      <div>
         <button onClick={getMemeImage}> Click me </button>
      </div>
   )
}

export default MainContent

I tried

its not working correct me anyone

import React, { useState } from 'react'
import Card from './Card'
import memesData from './memesData';
import './MainContent.css';

function MainContent() {

   const [data, setData] = useState('')

   function getMemeImage() {

      const memesArray = memesData.data.memes
      const randomNumber = Math.floor(Math.random() * memesArray.length)
      const n = memesArray[randomNumber].name
      console.log(n)
      setData(data + n)
   }

   return (
      <div>
         <button onClick={getMemeImage}> Click me </button>
         <h1>{setData}</h1>
      </div>
   )
}

export default MainContent

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

import React, {useState} from 'react'
import Card from './Card'
import memesData from './memesData';
import './MainContent.css';

function MainContent() {

const [state, setState] = useState();

   function getMemeImage() {

      const memesArray = memesData.data.memes;
      const randomNumber = Math.floor(Math.random() * memesArray.length);
      const n = memesArray[randomNumber].name;
      setState(n);
      console.log(n)
   }

   return (
      <div>
         <button onClick={getMemeImage}> Click me </button>
         <h1>{state}</h1>
      </div>
   )
}

export default MainContent
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading