Reputation:
I am trying to achieve a modal popup(which is stored in postview class) to appear when a onclick is called in any post on postcontainer class. I am new to react, so I would love your suggestion on improving code.
Class 1 (PostCointainer) This is main class which shows multiple post from an array. I want the modal to appear from class 2 when any post is clicked
import React, { Component, useState } from 'react';
import '../App.css';
import PostView from './PostView';
function RenderPost({posts}) {
return (
<div className="post-holder shadow-sm p-3 mb-4 bg-white rounded" key={posts.id} onClick={class postview class 2}>
</div>
);
}
const PostContainer = props => {
const menu = props.posts.map(post => {
return (
<RenderPost posts={post} />
)
});
return (
<div className="container-fluid">
<div className="row justify-content-center">
<PostView />
{menu}
</div>
</div>
);
}
export default PostContainer;
Class 2 (post View)
class PostView extends Component {
constructor(props) {
super(props);
this.state = {
isModalOpen : true,
}
this.toggleModal = this.toggleModal.bind(this);
}
toggleModal(e) {
e.stopPropagation()
this.setState({
isModalOpen: !this.state.isModalOpen
});
}
render() {
return (
<div className="shadow-sm p-2 mb-2 bg-white">
<div
className="modal"
style={{display: this.state.isModalOpen ? 'block' : 'none' }}
onClick={this.toggleModal} >
<div
className="modal-content"
onClick={ e => e.stopPropagation() } >
<span
className="close"
onClick={this.toggleModal}
>×
</span>
<div className="container">
<h3 className="form-header">Hello</h3>
</div>
</div>
</div>
</div>
);
}
}
export default PostView;
Upvotes: 0
Views: 505
Reputation: 375
This can be simply acheived by maintaining a state variabe for post click in the parent component and passing it via prop to child.
import React, { Component, useState } from 'react';
import '../App.css';
import PostView from './PostView';
const PostContainer = props => {
const [post, setPost] = useState(false);
function RenderPost({posts}) {
return (
<div className="post-holder shadow-sm p-3 mb-4 bg-white rounded" key={posts.id} onClick={setPost(posts)}>
</div>
);
}
const menu = props.posts.map(post => {
return (
<RenderPost posts={post} />
)
});
return (
<div className="container-fluid">
<div className="row justify-content-center">
<PostView post={post} />
{menu}
</div>
</div>
);
}
export default PostContainer;
constructor(props) {
super(props);
this.state = {
isModalOpen : !!props.post,
}
this.toggleModal = this.toggleModal.bind(this);
}
And you can use the same post prop to render post in render function of your child component. Hope it helps!!
Upvotes: 1