I am trying to make react app where I have a button that causes an h1 element on my screen to display a joke generated from an npm package. I can tell npm package has installed successfully (by checking my console.log element), but i cant seem to get the button to change the existing h1. I receive no error message when the code compiles.
import React from 'react' var oneLinerJoke = require('one-liner-joke'); var getRandomJoke = oneLinerJoke.getRandomJoke(); console.log(getRandomJoke) function getJoke(){ let h1 = document.querySelector('h1'); let changedH1 = document.getElementById('jokeline').innerHTML={getRandomJoke}; return changedH1; } const Template = (props) => { return( <div> <h1 id='jokeLine'>Click the button to read a joke</h1> <button onclick= 'getJoke()'>Get ready to laff</button> </div> ) } export default Template
Use React state to save the joke and display it to screen. Don't directly manipulate DOM if not really required. I have updated the code with state you can check this by running at your end.
I have use react hooks to use state functionality in React's functional component.
import React, {useState} from 'react' import oneLinerJoke from 'one-liner-joke'; const Template = (props) => { const [joke, setJoke] = useState(null); const getJoke = () => { setJoke(oneLinerJoke.getRandomJoke()); } return( <div> <h1 id='jokeLine'>{joke? joke: 'Click the button to read a joke'}</h1> <button onclick= 'getJoke()'>Get ready to laff</button> </div> ) } export default Template
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.