UPDATE: Turns out everything was working fine. I just had an error in my className Ternary that was causing the class not to apply. However, could someone explain why onClick does not appear on the <div> in the inspector?
I have a react component in which I would like to render a <div> with an onClickevent. However, the onClickis not rendering for some reason. I have no errors in the console other than the warning: Each child in an array or iterator should have a unique "key" prop.
The <div> that actually renders looks like this: <div id="1" class="unselected">Peppered Chicken</div>
My code looks like this. Thoughts?
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (<div><RecipesList/></div>)
}
}
class RecipesList extends React.Component {
constructor(props) {
super(props);
this.state = {
recipes: [{recipes:[]}],
selectedRecipe: null
};
this.setRecipeAsSelected = this.setRecipeAsSelected.bind(this)
}
componentDidMount() {
fetch('/recipes')
.then(response => response.json())
.then(recipes => this.setState({recipes}));
}
setRecipeAsSelected(recipeID) {
this.setState({selectedRecipe: recipeID})
}
render() {
return (
<div>
{this.state.recipes[0]["recipes"].map((recipe, index) => {
return <Recipe setRecipeAsSelected={this.setRecipeAsSelected} selectedRecipe={this.state.selectedRecipe} recipe={recipe} id={index}/>
})}
<Generate/>
</div>
)
}
}
class Recipe extends React.Component {
constructor(props){
super(props);
this.setThisAsSelected = this.setThisAsSelected.bind(this)
}
setThisAsSelected() {
this.props.setRecipeAsSelected(this.props.id)
}
render() {
return (
<div onClick={this.setThisAsSelected} key={this.props.id} id={this.props.id} className={this.props.selectedRecipe === this.props.key ? "bg-primary" : "test"}> {this.props.recipe} </div>
)
}
}
class Generate extends React.Component {
render() {
return (
<div>
<button>GENERATE</button>
</div>
)
}
}
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
<App/>,
document.body.appendChild(document.createElement('div')),
)
});
Each child in an array or iterator should have a unique "key" propTo fix this, add the key in yourRecipleList's render method, when mapping through to the<Recipe />components. ie,<Recipe ... key={index} />- smeclass="unselected"come from ? It is not in the code. - leaf