Reputation: 11153
I'm using an array of string categories to create input checkboxes. Checking the input box tells me you want to include that category and unchecking an input box tells me you don't want to include that category.
Problem is, I don't know what the ref of the object that is being clicked. How do I figure out the ref?
I'd like to pass this ref back up to my parent class so that it can find the index of the 'ref' in my array of categories, and splice that out. The result being that my filteredCategories array will remove the item when it is there and add it if it isn't
var HeaderCategories = React.createClass({
handleChange:function(e){
// I know what was clicked through e.target
// but I'd like to know the ref of what was clicked
// so that I can do somthing like the below:
this.props.filterTable(this.refs[e.target.ref])
},
render: function(){
var categories = this.props.allCategories.map(function(category){
return (
<label key={category}>{category}
<input type="checkbox" ref={category} onChange={this.handleChange}/>
</label>
)}.bind(this))
return (
<div className="categories __header" >{categories}</div>
);
}});
var Table = React.createClass({
allCategories: ["apples","oranges","bananas"]
componentDidMount:function(){
this.setState({filteredCategories:this.allCategories})
},
getInitialState:function(){
return {filteredCategories:this.allCategories}
},
filterTable:function(category){
// If I have the ref then I can use a splice and remove it from my filtered Categories
//this is pseudo code, havent checked if it works
var index = filteredCategories.indexOf(category)
var filteredCategories.splice(index,filteredCategories.length)
this.setState(filteredCategories:filteredCategories)
},
render:function(){
return <Header filterTable={this.filterTable} allCategories={this.allCategories}>
}
})
Upvotes: 2
Views: 691
Reputation: 3485
There is not a good way to get a reference to a component from the event param of the onClick callback. You best option is to curry either the category index or name to the callback like this (in this example, I'm passing back just the index)
handleChange:function(e, categoryIndex){
// `categoryIndex` was curried in the click handler
// of each checkbox in the render function below so
// the filterTable callback should accept the index.
this.props.filterTable(categoryIndex);
},
render: function(){
var categories = this.props.allCategories.map(function(category, index){
return (
<label key={category}>{category}
<input type="checkbox" ref={category} onChange={this.handleChange.bind(this, index)}/>
</label>
)}, this); // map's second param is thisArg
return (
<div className="categories __header" >{categories}</div>
);
Upvotes: 2