I'm new to web development and decided to learn ReactJs. I am trying to create a random quote generator as a part of freecodecamp's frontend libraries project. Problem: I have a react component that fetches the quotes from a website and then displays a random quote on the screen. I also have a button outside of the component whose sole purpose is to get a new code and display it onscreen. How do I refresh the react component whenever I click the button? Any help is appreciated!:D Here's my component:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
quote: ''
};
}
componentDidMount() {
fetch("https://type.fit/api/quotes")
.then(res => res.json())
.then(
(result) => {
this.setState({
quote: result[Math.floor(Math.random() * result.length)]
});
},
)
}
render() {
return (
<p id = 'reactQuote'>{this.state.quote.text}< /p>
);
}
}
ReactDOM.render( MyComponent />, document.getElementById('text'))
<div id="text"></div>
<button id='new-quote'>New Quote</button>