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
>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