Reputation: 51
I'm learning application development with Meteor and React and have run into a hurdle. I want users to be able to click on an element and have that change the class of another element. If I was creating a site without Meteor or React I would use a jQuery function like this:
$("#button").click(function(){
$("#target").removeClass("hidden");
});
I can't seem to figure out how to use jQuery in my React application (but copying the code into chrome web console works) so I started googling and found that it isn't recommended to use jQuery or to directly manipulate the DOM at all while using React. I don't understand much of how React's virtual DOM works at this stage.
So my question is: what is the correct way to replicate what this jQuery code does in a React application?
Upvotes: 1
Views: 282
Reputation: 1242
I recommend You to combine classnames (link) and state, so You can do it like this:
class Example extends React.Component {
constructor() {
super();
this.state = {
clicked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ clicked: true });
}
render() {
return (
<div className={classNames('foo', { hidden : this.state.clicked })}>
<button onClick={this.handleClick} >BUTTON</button>
</div>
);
}
}
ReactDOM.render(
<Example />,
document.getElementById('example')
);
If state clicked
is false
, class hidden
is not active on a specific element.
Upvotes: 2