Reputation: 393
I am trying to put h1 heading, but if I put the only heading and comment out buttons then heading doesn't print. And if I comment heading then the buttons does not print. But together doesn't print anything. Any suggestion?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
drumPads : [
{
id: "Q",
src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3",
beat: "Heater-1",
},
{
id: "W",
src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3",
beat: "Heater-2"
},
}
handleClick(id, beat) {
return () => {
document.getElementById(id).play();
this.setState({
beatName: beat,
});
};
}
render() {
return (
<Fragment>
<h1>DrumMachine</h1>
<div>
this.state.drumPads.map((button, i) =>
<button key={i} onClick={this.handleClick(button.id, button.beat)}><h1>{ button.id }</h1>
<audio id={button.id} src={button.src} />
</button>
)
</div>
</Fragment>
)
}
}
ReactDOM.render( <App />,
document.getElementById("root")
)
Upvotes: 0
Views: 161
Reputation: 6482
You need to have a single parent element as opposed to <div></div>
followed by another <div></div>
. You should use a React.Fragment
as the parent element:
render() {
return (
<>
<h1>Drum Machine</h1>
<div>
//other stuff
</div>
</>
);
}
There were also some syntax errors in the code, namely:
this.state
in constructormap
expression in render()
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
drumPads: [
{
id: "Q",
src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3",
beat: "Heater-1"
},
{
id: "W",
src: "https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3",
beat: "Heater-2"
}
]
};
}
handleClick(id, beat) {
return () => {
document.getElementById(id).play();
this.setState({
beatName: beat
});
};
}
render() {
return (
<React.Fragment>
<h1>DrumMachine</h1>
<div>
{this.state.drumPads.map((button, i) =>
<button key={i} onClick={this.handleClick(button.id, button.beat)}>
<h1>{button.id}</h1>
<audio id={button.id} src={button.src} />
</button>
)}
</div>
</React.Fragment>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 2