I have a component:
class CommentBox extends Component {
render() {
return (
<div>
<p>Some comment</p>
<a>Post a reply to this comment</a>
</div>
<ReplyForm />
)
}
}
I need this ReplyForm
to be hidden on initial load. How to trigger it's state by clicking on a tag?
To show or hide another component on click in React: Set the onClick prop on an element. When the element is clicked, toggle a state variable that tracks if the component is shown. Conditionally render the component based on the state variable.
The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app. In addition, React event handlers appear inside curly braces.
We have to set initial state value inside constructor function and set click event handler of the element upon which click, results in changing state. Then pass the function to the click handler and change the state of the component inside the function using setState.
You should add some flag to the state of CommentBox
. And if value of this flag is false
when don't show ReaplyFrom
and vice versa. Heres the code and working example http://codepen.io/anon/pen/KzrzQZ
class ReplyForm extends React.Component {
constructor() {
super()
}
render(){
return(
<div>I'm ReplyForm</div>
)
}
}
class CommentBox extends React.Component {
constructor() {
super();
this.state = {
showReply: false
}
}
onClick(e){
e.preventDefault();
this.setState({showReply: !this.state.showReply})
}
render() {
return (
<div>
<p>Some comment</p>
<a onClick={this.onClick.bind(this)} href='#'>Post a reply to this comment</a>
{this.state.showReply && < ReplyForm / >}
</div>
)
}
}
How about this?
class CommentBox extends Component {
constructor() {
super();
this.state = {
showForm: false
}
}
render() {
const showHide = {
'display': this.state.showStatus ? 'block' : 'none'
};
const showReplyForm = () => {
this.setState({showForm: true});
};
return (
<div>
<div>
<p>Some comment</p>
<a onClick={showReplyForm}>Post a reply to this comment</a>
</div>
<div style={showStatus}>
<ReplyForm />
</div>
</div>
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With