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
CodePudding user response:
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
CodePudding user response:
Easiest way is to let getMemeImage
return the value, so you can easily pass it to setData
end as initial value.
const { useState, useEffect } = React;
const Example = () => {
const names = [ "foo", "bar", "joe", "someone", "else" ];
function getMemeImage() {
const memesArray = [ ...names ]
const randomNumber = Math.floor(Math.random() * memesArray.length)
const n = memesArray[randomNumber]
return n;
}
const [data, setData] = useState(getMemeImage())
return (
<div>
<button onClick={() => setData(getMemeImage())}> Click me </button>
<h1>{data}</h1>
</div>
)
}
ReactDOM.render(<Example />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>