Reputation: 37
".b2" is classname of a button. "#subscribe" is the id of a div blank container. the jquery hides the div container on clicking the button. how to convert this into reactjs ?
$(".b2").click(function(){
$("#subscribe").hide();
});
Upvotes: 0
Views: 58
Reputation: 98
ReactJS is state and component based and you can use state to control UI in your view.
For a good introduction to how state works check out the ReactJS docs (specifically the State and Lifecycle section)
But you can achieve something above with the following: (untested code)
state = { visible: false }
<Button onClick={this.setState=({visible: !this.state.visible})}>Toggle me!</Button>
<Component visible={this.state.visible} />
The above will toggle the visibility of said component. Note the visibility
prop being passed in to <Component>
. You can access this inside the component with props
.
More on props in their docs.
Upvotes: 1
Reputation: 1838
In ReactJS you will need three things:
1) A stateful component with a boolean in the state, initialized to true. This boolean will be used to show/hide the container.
2) A function to update the state of the boolean to false.
3) A render method to render the container based on the state of the boolean and the button to trigger the function.
All together you will need something like this:
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
showContainer: true
}
}
hideContainer() {
this.setState({ showContainer: false });
}
render() {
return (
<div>
{this.state.showContainer && <div>MyContainer</div>}
<button onClick={() => this.hideContainer()}>Hide container</button>
</div>
)
}
}
Upvotes: 1
Reputation: 2848
Use state to set the style of the element like this.
import React, { Component } from 'react';
import { render } from 'react-dom';
class App extends Component {
constructor() {
super();
this.state = {
show: false
};
}
render() {
const { show } = this.state
return (
<div>
<p style={{ display: show ? "" : "none"}}>
Start editing to see some magic happen :)
</p>
<button onClick={() => this.setState({show: !show})}>
{show ? 'Hide' : 'Show'}
</button>
</div>
);
}
}
render(<App />, document.getElementById('root'));
Live example here https://stackblitz.com/fork/react
Upvotes: 0