How to alter another component's state with a different component? (React)

Hello. I am very new to React. and actually currently working on the random quote machine project using react. i am having trouble with the “new quote” button. i originally had it working but they were both nested inside the same component. so, it was causing formatting issues. so ive been trying to take the new quote button and put it inside a different component and calling the child component from the parent but im struggling with the proper syntax. can someone help me out?

here’s a link to my project so far… https://codepen.io/ywvlfy/pen/ZEzdVgq

You normally would only call ReactDOM.render once, with the components somehow nested in a root component. I’m not sure if there’s any way for components in different ReactDOM.render calls to communicate.

Layout shouldn’t be too much of an issue, since the JSX elements will appear in the DOM pretty much the same way as if it was regular HTML.

thank you for the advice. i will apply the necessary changes. guess i was approaching the problem incorrectly. :slight_smile:

Using what @kevcomedia said, your HTML section would only have the following in it:

<div id="quote-machine"></div>

and your JS section would look like:

class MyQuote extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			quote: ""
		};
		this.update = this.update.bind(this);
	}
	update() {
		fetch("https://api.kanye.rest")
			.then(response => response.json())
			.then(x => this.setState({ quote: x.quote }));
	}
	componentDidMount() {
		this.update();
	}
	render() {
		return (
			<div id="quote-box">
				<div id="box">
					<h1 className="title-box">Kanye West Quotes</h1>
				</div>
				<img class="logo" src="https://live.staticflickr.com/29/61886374_f4e22fd4b4_n.jpg" alt="Kanye West" />
				<script	async src="//embedr.flickr.com/assets/client-code.js"	charset="utf-8"	/>
				<div id="text" class="speech-box">
					<div>
						"{this.state.quote}"
						<button id="new-quote" onClick={this.update}>New Quote</button>
					</div>
				</div>
				<div id="author">
					All Quotes are originally said by the Louis Vuitton Don himself.
				</div>
			</div>
		);
	}
}

ReactDOM.render(<MyQuote />, document.getElementById("quote-machine"));

1 Like

thank you my friend. i was still having trouble. i will post again in this thread when i have it all sorted out. :100: