I have the following parent and child components. I want to run the changeBackground function every time the button in the child component (<NewQuoteButton />) is clicked but I don't know how to pass this information to the parent component. Can anyone please help?
//parent component
class App extends React.Component {
constructor(props) {
super(props)
this.state ={
primary: '',
prmaryDark: ''
}
}
changeBackground = () => {
let randomNum = Math.floor(Math.random()*backgroundColors.length)
this.setState = {
primary: backgroundColors[randomNum].main,
prmaryDark: backgroundColors[randomNum].dark
}
}
render() {
return (
<div className="App">
<QuoteBox />
</div>
);
}
}
//child component
export default function QuoteBox() {
const [newQuote, setNewQuote] = useState('');
const [author, setAuthor] = useState('');
const fetchRandomQuote = () => {
fetch(url)
// some method
}
return (
<div className="QuoteBox" >
<Text quoteText={newQuote} author={author} />
<Banner>
<Links />
<NewQuoteButton onClick={fetchRandomQuote} className="NewQuoteButton Button" />
</Banner>
</div>
);
}
//parent component
class App extends React.Component {
constructor(props) {
super(props)
this.state ={
primary: '',
prmaryDark: ''
}
}
changeBackground = () => {
let randomNum = Math.floor(Math.random()*backgroundColors.length)
this.setState = {
primary: backgroundColors[randomNum].main,
prmaryDark: backgroundColors[randomNum].dark
}
}
render() {
return (
<div className="App">
<QuoteBox handleColorChange={this.changeBackground} />
</div>
);
}
}
//child component
export default function QuoteBox(props) {
const [newQuote, setNewQuote] = useState('');
const [author, setAuthor] = useState('');
const fetchRandomQuote = () => {
props.handleColorChange();
fetch(url)
// some method
}
return (
<div className="QuoteBox" >
<Text quoteText={newQuote} author={author} />
<Banner>
<Links />
<NewQuoteButton onClick={fetchRandomQuote} className="NewQuoteButton Button" />
</Banner>
</div>
);
}
If you just want to run your changeBackground function when the button is clicked then call the function in your fetchRandomQuote function.