How to show a popup modal on page load in React js functional component - node.js

How to show a popup modal on page load in React js functional component.basically when the page loads the popup or modal should be visible automatically without any click

Most modals will have a prop to specify whether or not the modal should be open. You can simply set this to true on initialization.
Consider an example using a Dialog from the React UI library MUI:
const SimpleDialog = (props) =>
{
const [open, setOpen] = useState(true)
return (
<Dialog open = {open}>
<DialogTitle>Title</DialogTitle>
<DialogContent>...</DialogContent>
</Dialog>
)
}
The open prop of the Dialog is based on the value of the state variable, which is initialized as true. You can change this value as needed through various Dialog actions. To learn more about MUI Dialogs, see the docs.
For information on useState, see the React docs.

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
modalState: true
};
this.handleShow = this.handleShow.bind(this);
}
handleShow() {
this.setState({ modalState: !this.state.modalState });
}
render() {
return (
<div>
<div className={"modal fade" + (this.state.modalState ? " show d-block" : " d-none")} tabIndex="-1" role="dialog">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">My Profile</h5>
<button type="button" className="close" onClick={this.handleShow}>
<span>×</span>
</button>
</div>
<div className="modal-body">...</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" onClick={this.handleShow}>Close</button>
<button type="button" className="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
ReactDOM.render(, document.getElementById('root'));
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

Related

I am having problems with setState

I'm working on a simple login site and to navigate between Login and Sign up site I made a state called "aktivSide" meaning "activeSite" which is supposed to determine whether the login site or the sign up site will display.
Whenever I click on the "Registrer Bruker" (sign up) button, I get this error message:
Uncaught TypeError: Cannot read properties of undefined (reading 'setState')
import planB from "./plan_b.json"
import logo from './bilder/logo.png'
import './App.css';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faEyeSlash, faEye } from '#fortawesome/free-solid-svg-icons'
import React from 'react';
class App extends React.Component {
//React
constructor(props) {
super(props);
this.state = {
aktivSide: "tom"
};
}
render() {
//JavaScript
return (
//jsx (javascript og HTML)
<>
<div onLoad={() => this.setState({ aktivSide: <LoggInn /> })} className="App">
<title>SpeedType</title>
<header className="App-header">
<div id="topp">
<img id="logoen" width={300} src={logo}></img>
</div>
<button onClick={() => console.log(this.state.aktivSide)}>state</button>
{this.state.aktivSide}
</header>
</div>
</>
)
function RegistrerBruker() {
return (
<>
<h1>Registrer Bruker</h1>
<input type="text" placeholder='brukernavn' className='input_text'></input>
<div className='passord'>
<input type="password" placeholder='passord' className='input_text'></input>
<FontAwesomeIcon className='eye_icon' id='eye_icon1' />
</div>
<p id='passordTekst'>tom</p>
<div className='knapper'>
<button className='knapper_login'><p>Logg Inn</p></button>
<button className='knapper_login'><p>Registrer deg</p></button>
</div>
</>
)
}
function LoggInn() {
//JavaScript
return (
//jsx
<>
<h1>Logg inn</h1>
<input type="text" placeholder='brukernavn' className='input_text'></input>
<div className='passord'>
<input type="password" placeholder='passord' className='input_text'></input>
<FontAwesomeIcon className='eye_icon' id='eye_icon1' />
</div>
<p id='passordTekst'>tom</p>
<div className='knapper'>
<button className='knapper_login'><p>Logg Inn</p></button>
<button onClick={() => this.setState({ aktivSide: <RegistrerBruker /> })} className='knapper_login'><p>Registrer deg</p></button>
</div>
</>
)
}
}
}
export default App;
I've tried adding:
this.aktivSide.bind(this);
to the constructor, but nothing will display.

"Gets unauthorized error after submitting correct token"

I just try to hit the API when like and dislike button is clicked , but I get unauthorized error after passing the authorization header.
What is the solution of this problem. There is post where all users can like or dislike. There is only unauthorized error, everything is true.
This is the screenshot of where the action is written.
This is the screenshot where the error is displayed.
`JavaScript code
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import {Link} from 'react-router-dom';
import { deltePost, addLike, deleteLike } from
class PostItem extends Component {
onDelteClick(postId)
{
this.props.deltePost(postId);
}
onLikeClick(id)
{
this.props.addLike(id);
}
onunLikeClick(id)
{
this.props.deleteLike(id);
}
render() {
const {post,auth,showActions}=this.props;
return (
<section className="container">
<div className="posts">
<div className="post bg-white p-1 my-1">
<div>
<a href="profile.html">
<img
className="round-img"
src="//www.gravatar.com/avatar/05434e5d678bc30625550497804f6d0e?s=200&r=pg&d=mm"
alt=""
/>
<h4>{post.name}</h4>
</a>
</div>
<div>
<p className="my-1">
{post.text}
</p>
<p className="post-date">
{post.date}
</p>
{showActions ?(<span>
<button onClick={this.onLikeClick.bind(this, post._id)} type="button" className="btn btn-light">
<i className="fas fa-thumbs-up"></i>
<span>{post.likes.length}</span>
</button>
<button onClick={this.onunLikeClick.bind(this, post._id)} type="button" className="btn btn-light">
<i className="fas fa-thumbs-down"></i>
</button>
<Link to={`/post/${post._id}`} className="btn btn-primary">
Comments <span className='comment-count'>{post.comments.length}</span>
</Link>
{post.user === auth.user.id ?(
<button
type="button"
onClick={this.onDelteClick.bind(this,post._id)}
className="btn btn-danger"
>
<i className="fas fa-times"></i>
</button>
):null}
</span>) :null}
</div>
</div></div>
</section>
)
}
}
PostItem.defaultProps={
showActions:true
}
PostItem.propTypes={
deltePost:PropTypes.func.isRequired,
deleteLike:PropTypes.func.isRequired,
addLike:PropTypes.func.isRequired,
post:PropTypes.object.isRequired,
auth:PropTypes.object.isRequired
}
const mapStateToProps= state =>({
auth:state.auth
})
export default connect(mapStateToProps,{deltePost,addLike,deleteLike})(PostItem)
`

How do I set up a comment reply feature in react.js in these codes?

So, I am using react, nodejs and mongodb to build a basic blog application.
So far, I have been able to add the comment feature and users can create, delete and edit comments. But I wanted to add the ability to reply to a comment. I added a 'Reply' text inside the area where I mapped the array of comments in my react.js component. So, when you click on the 'Reply' it toggles the textbox for reply. That means on first click, the textbox to reply to that specific comment shows up, on second click, that textbox hides.
The problem now is that the toggle is working for all the mapped array of comments. I am trying to assign the specific '_id' to the 'Reply' text and pass it to the textbox for the user to write their reply to that specific comment using the '_id'. This should prevent the reply textbox from toggling for all the comments at the same time. How best can I get this done? Here are my codes:
The useState that hides and shows the textbox
const [showReply, setShowReply] = useState(false)
The function that toggles the useState
const handleShowReplyComment = (id) =>{
console.log(id)
if(id){
setShowReply(!showReply)
console.log(id)
}
}
This function picks the '_id' of the comment that I clicked. But how to pass that '_id' to the textbox is my challenge.
return (
<div className="comment">
<h5 className='users-comment'>Users comments</h5>
{comments.map((singleComment, index)=>{
console.log(singleComment)
const {author, commentdescription, _id, createdAt} = singleComment
return(
<>
{updateComment == _id ?
<div className='comment-div' key={_id} >
<textarea className='comment-wrapper' type='text'
onChange={(e) => setCommentDescription(e.target.value)} value={commentdescription2}>
</textarea>
<button className={isLoading ? 'comment-btn-no-cursor comment-btn': 'comment-btn'}onClick={() => handleCommentUpdate(_id)}>Update Post</button>
{error && <p>what happened?</p> }
</div>
:
<div className='displayed-comments'key={_id}>
<div className="commentPic">
<img className="user-pics" src={PF + singleComment.author.profilePicture} alt="" />
</div>
<div className="comment-info">
<div className="comment-author-div">
<div className='comment-author-date-info'>
<h4 className="comment-author">{singleComment.author.username}</h4>
<p className="comment-date">{new Date(singleComment.createdAt).toDateString()}
</p>
</div>
{
singleComment.author.username == user?.username && <div className="comment-edit-delete-div">
<i className="singlePostIcon fas fa-edit" onClick={() => {setUpdateComment(_id); setCommentDescription(commentdescription)}} ></i>
<i className={isLoading? "cursor-not-allowed singlePostIcon far fa-trash-alt":"singlePostIcon far fa-trash-alt" } onClick={() => handleCommentDelete(_id)} ></i>
</div>
}
</div>
<p className="comment-content">{singleComment.commentdescription}</p>
<div>
</div>
<h5 className="reply-comment" onClick={() => handleShowReplyComment(_id)}>Reply</h5> //this is the text with the toggle onClick function that toggles the useState called 'showReply'
{showReply && <div className='reply-div'>//this is the textbox with the useState 'showReply'.
<textarea className='comment-wrapper '>
</textarea>
</div>}
</div>
</div>
}
</>
)
})}
</div>
)

Passing props a on button click

<Slider {...settings}>
{this.state.featuredMovies.map(movie =>
<div className="" key={movie._id}>
<Card inverse style={{padding: "10px", width: "90%"}}>
<CardImg src={`/files/${movie.thumbnail}`} alt="Card image cap" />
<CardImgOverlay className="movie-list-overlay">
<CardTitle>{movie.MovieName}</CardTitle>
<CardText>{movie.Description}</CardText>
<CardText>
<small>
<a href="watch">
<Button className="btn-fill btn-movie " color="primary" onClick={movie}>
Watch
</Button></a></small>
</CardText>
</CardImgOverlay>
</Card>
</div>
)}
</Slider>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
i want to pass the movie props on button click to the watch component so the watch component
class WatchMovies extends React.Component {
ComponentDidMount(){
const { player } = this.refs.player.getState();
}
handleDelete = e => {
console.log(this.refs.player.play())
}
handleD = e => {
const {player} = this.refs.player.getState()
console.log(player.currentTime)
console.log(this)
}
render() {
return (
<>
<div className="container-fluid bg-black">
<div className="col-md-12 mx-auto pt-5">
<Row className="" >
<div className="col-md-12 mx-auto py-5">
<Player
ref="player"
width="80%"
playsInline
poster="/assets/bg5.jpg"
src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4"
position="center"
LoadingSpinner
onEnded={() => console.log("ended")}
/>
<Button onClick={this.handleDelete}>D </Button>
<Button onClick={this.handleD}>D </Button>
</div>
</Row>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
i want to pass the movie props on button click to the watch component so the watch component. Watch component is where you will be redirect to watch the movie you selected from the movielist component above
Your onClick needs to be a function
<Button onClick={() => this.doSomething(movie)} />
Then you can access the movie value in that function
const doSomething = (movie) => {
//Do some stuff with the movie
}

Error: onSubmit doesn't work on reactjs jsx render method

I'm trying to create a form inside a react component on node server but my onSubmit attr isn't being compiled. any thoughts why?
Here is my code:
/** #jsx React.DOM **/
var React = require('react');
module.exports = UserForm = React.createClass({
handleSubmit: function (e) {
e.preventDefault();
console.log("teste");
},
render : function () {
return (
<div className="container">
<form onSubmit= { this.handleSubmit } className="section">
<button className="btn waves-effect waves-light" type="submit">
Entrar
<i className="mdi-content-send right"></i>
</button>
</form>
</div>
)
}
});
and the output for this rendered code is this :
<div class="container" data-reactid=".1vxqgp72xa8" data-react-checksum="-1342114635">
<form class="section" data-reactid=".1vxqgp72xa8.0">
<button class="btn waves-effect waves-light" type="submit" data-reactid=".1vxqgp72xa8.0.1">
<span data-reactid=".1vxqgp72xa8.0.1.0">Entrar</span>
<i class="mdi-content-send right" data-reactid=".1vxqgp72xa8.0.1.1"></i>
</button><div class="preloader-wrapper big active" data-reactid=".1vxqgp72xa8.0.2">
</form>
</div>
this may be a silly error, can someone help me finding it?
THanks you all
Simple enough, you aren't providing a callback. It should look like this:
<form onSubmit={ this.handleSubmit } className="section">
Edit:
After a little discussion in the comments, it became clear you weren't mounting the app on the front-end after delivering the server rendered html to the browser. After the page has loaded call this:
React.render(React.createElement(UserForm, {}), domElement);

Resources