How to show a button after 10 seconds using react hooks - reactjs

I am very new to React hooks can someone please help me how to show a button after 10 seconds I tried a little but I don't know how to implement it.
This is my code
import React, { useState, useEffect } from 'react';
import './App.css';
const App = () => {
const [show, setShow] = useState(false)
useEffect(() => {
});
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div className='main'>
<button className='btn btn-primary'>Click here</button>
</div>
</div>
</div>
</div>
)
}
export default App
```

Try this:
useEffect(() => {
setTimeout(() => setShow(true), 10000);
}, []); []: this is important as it will run this effect only once on component load
and use it like:
{show && <button className='btn btn-primary'>Click here</button>} // this will show the button when show state will be true

Related

How to add bootstrap moadal in reactJs calendar?

I am working in MERN project where i want to add a bootstarp modal in react calendar. i want that, if any any user clicks on any date a modal should popup. but i don't know how to proceed. please suggest me some good way to achieve this.
my code
import React, { useState } from 'react'
import Calendar from 'react-calendar'
import 'react-calendar/dist/Calendar.css';
import moment from 'moment'
export default function AddMember() {
const [dateState, setDateState] = useState(new Date())
const changeDate = (e) => {
setDateState(e)
}
return (
<>
<div className='container mt-5'>
<div className='row'>
<div className='col-sm-8 col-md-8 col-lg-8'>
<Calendar
value={dateState}
onChange={changeDate}
/>
<p>Current selected date is <b>{moment(dateState).format('MMMM Do YYYY')}</b> </p>
</div>
</div>
</div>
</>
)
}
You can achieve by setting modal state in your changeDate function like this.
import React, { useState } from 'react'
import Calendar from 'react-calendar'
import 'react-calendar/dist/Calendar.css';
import moment from 'moment'
// import Modal from react-bootrap
import Modal from 'react-bootstrap/Modal';
export default function AddMember() {
const [dateState, setDateState] = useState(new Date())
const [show, setShow] = useState(false)
const handleClose = () => setShow(false)
const handleShow = () => setShow(true)
const changeDate = (e) => {
setDateState(e)
handleShow()
}
return (
<>
<div className='container mt-5'>
<div className='row'>
<div className='col-sm-8 col-md-8 col-lg-8'>
<Calendar
value={dateState}
onChange={changeDate}
/>
<p>Current selected date is <b> {moment(dateState).format('MMMM Do YYYY')}</b> </p>
</div>
</div>
</div>
<Modal show={show} onHide={handleClose}>
// your modal content goes here
</Modal>
</>
)
}
Now whenever user clicks or select a date a modal will popup. Happy coding :-)

Keep catching same value within map() method recurring

In my project, I have a component for rendering all the records from a table in the database. I'm using map() method to populate the records to the page. The components with values were displayed all right on the page. However, in the console, the console.log result is recurring and will never stop.
Here is my code in the component which using map(). CourseCard.js
import {FontAwesomeIcon} from "#fortawesome/react-fontawesome";
import fontawesome from "#fortawesome/fontawesome";
import {faGraduationCap, faArrowAltCircleRight, faUser} from '#fortawesome/fontawesome-free-solid'
import {useNavigate, useParams} from "react-router-dom";
fontawesome.library.add(faGraduationCap, faArrowAltCircleRight, faUser);
function CourseCard({courses}) {
let navigate = useNavigate();
const routeCourseDetail = (id) => {
return () => {
let path = `/courses/detail/${id}`;
navigate(path);
}
}
return (
<div>
{courses.map((course) => {
return <div className="col-sm col-md col-lg">
<div className="card blue" key={course.id} onClick={routeCourseDetail(course.id)}>
<div className="inner">
<h1 style={{color: "white"}}>{course.name}</h1>
<h2 style={{color: "white", marginTop: "-0.5em"}}>{course.level}</h2>
</div>
<div className="icon" style={{color: "white"}}>
{/*<FontAwesomeIcon icon="fa-user" />*/}
<FontAwesomeIcon icon="graduation-cap"/>
</div>
<div className="footer">
More info <FontAwesomeIcon icon="arrow-alt-circle-right"/>
</div>
</div>
</div>
})}
</div>
)
}
export default CourseCard;
And the code for making the component formed in a matrix. CourseMatric.js
import React, {useEffect, useState} from "react";
import CourseCard from "./CourseCard";
import {useNavigate} from "react-router-dom";
import axios from "axios";
function CourseMatrix() {
let navigate = useNavigate();
const routeAdd = () => {
let path = "./new";
navigate(path);
}
const [coursesList, setCoursesList] = useState([]);
useEffect(() => {
axios.get(`http://localhost:3001/courses`).then((response) => {
setCoursesList(response.data);
console.log(response.data);
})
});
return (
<div className="main_content grid-2">
<div className="wrapper">
<CourseCard courses={coursesList}/>
</div>
<div className="new-line">
<button className="green_bt option_list round mr" onClick={routeAdd}>Add
</button>
</div>
</div>
)
}
export default CourseMatrix;
Anyone helps me to figure out which part is not correct to cause this problem to occur? Many thanks.
You need to add dependency in useEffect :
useEffect(() => {
axios.get(`http://localhost:3001/courses`).then((response) => {
setCoursesList(response.data);
console.log(response.data);
})
},[]);
useEffect asks for dependency so that it executes the effect only when the value is changed. The empty [] dependency will only execute the effect once.
Since you didn't add any dependency , the effect was getting executed on every re-render causing infinite loop (setCoursesList(response.data) was causing re-render) .

React useState hook only updates once onClick

I am trying to toggle true/false in my component using useState but I've noticed it only toggles one time and does not go back and forth. On clicking the component, it toggles true but then it won't toggle back to false. Any ideas on how to solve?
const [sound, setSound] = useState(false);
return (
<div>
<ReactPlayer
...
muted={sound}
onClick={() => {
setSound(!sound);
console.log("on click", sound);
}}
/>
</div>
)
EDIT
Thanks for the replies, I think the issue was the anon function, I solved it by doing this
onClick={() => {
setSound((sound) => !sound);
console.log("on click", sound);
}}
import React, {useState} from 'react';
import './App.css';
const ReactPlayer = ({muted, onClick}: {muted: boolean, onClick: () => any}) => {
return (
<div>
<button onClick={onClick}>Test</button>
<p>{muted.toString()}</p>
</div>
)
}
function App() {
const [sound, setSound] = useState(false);
return (
<div className="App">
<ReactPlayer
muted={sound}
onClick={() => {
setSound(!sound);
console.log("on click", sound);
}}
/>
</div>
);
}
export default App;
This code works perfectly, I don't know what you have in your ReactPlayer component, but this should work
As of Chrome 66, videos must be muted in order to play automatically. Some players, like Facebook, cannot be unmuted until the user interacts with the video, so you may want to enable controls to allow users to unmute videos themselves. Please set muted={true}. see docs for more info
Check the live code here in sandbox link
import ReactPlayer from "react-player";
import React, { useState } from "react";
// Render a YouTube video player
export default function App() {
const [play, setPlay] = useState(true);
return (
<div className="App">
<ReactPlayer
muted={play}
url="https://www.youtube.com/watch?v=9DDX3US3kss"
/>
Click to Mute or Unmute --
<button style={{ margin: "15px" }} onClick={() => setPlay(!play)}>
Mute/UnMute
</button>
</div>
);
}

How to hide a button when I click the button in react using functional components

By default I am trying to show button, Now I am trying to hide button when I click the buton in react using functional components.
This is my code
This is App.js
import React, { useState } from 'react';
import Parent from './Parent/Parent';
import './App.css';
function App() {
return (
<div className="App">
<Parent></Parent>
</div>
);
}
export default App;
This is Parent.js
import React, { useState } from 'react';
import './Parent.css';
const Parent = () => {
const [show, hide] = useState(true)
const hideButton = () => {
hide(false)
}
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div className='one'>
<button show ={show} onClick={hideButton} className='btn btn-primary'>Click here</button>
</div>
</div>
</div>
</div>
)
}
export default Parent
You need to do ternary condition to show and hide value:
{show && <button onClick={hideButton} className='btn btn-primary'>Click here</button>}
Full code:
import React, { useState } from "react";
import "./styles.css";
const Parent = () => {
const [show, hide] = useState(true);
const hideButton = () => {
hide(false);
};
return (
<div className="container">
<div className="row">
<div className="col-12">
<div className="one">
{show && (
<button onClick={hideButton} className="btn btn-primary">
Click here
</button>
)}
</div>
</div>
</div>
</div>
);
};
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Parent />
</div>
);
}
Here is the demo: https://codesandbox.io/s/romantic-newton-1wvl1?file=/src/App.js:0-678

"Reactjs" How to create a modal inside a functional component without using hooks

Can we create a toggle-able modal in a functional component without using hooks. Actually I'm trying to design a modal in a functional component but I couldn't achieve what I tried for. And on google, all I could find is hooks.
here's what I wrote but its not working
import React from 'react';
import { Card, CardImg, CardImgOverlay, CardBody, CardText, CardTitle, Breadcrumb, BreadcrumbItem, Button, Modal, ModalHeader } from 'reactstrap';
import { Link } from 'react-router-dom';
let isModalOpen = false;
const toggleModal = () => {
isModalOpen = !isModalOpen;
console.log(isModalOpen);
}
function RenderComments({comments}) {
if(comments!=null){
const list = comments.map((comment) =>{
let options = { year: 'numeric', month: 'long', day: 'numeric' };
let dt = new Date(comment.date);
return (
<li key={comment.id}>
{comment.comment}<br/><br/>
-- {comment.author}, {dt.toLocaleString('en-US', options)}
<br/><br/>
</li>
);
});
return(
<div className="col-12 col-md-7 mt-3 mb-3">
<h4>Comments</h4>
<ul className="list-unstyled">
{list}
</ul>
<Button onClick={toggleModal} outline color="secondary"><span className="fa fa-pencil"></span> Submit Comment</Button>
</div>
);
}else{
return (<div></div>);
}
}
const DishDetail = (props) => {
if(props.dish!=undefined){
return(
<div className="container">
<div className="row">
<Breadcrumb>
<BreadcrumbItem><Link to="/menu">Menu</Link></BreadcrumbItem>
<BreadcrumbItem active>{props.dish.name}</BreadcrumbItem>
</Breadcrumb>
<div className="col-12">
<h3>{props.dish.name}</h3>
</div>
<RenderDish dish = {props.dish} />
<RenderComments comments = {props.comments} />
</div>
<Modal isOpen={isModalOpen} toggle={toggleModal}>
<ModalHeader toggle={toggleModal}>
Login
</ModalHeader>
</Modal>
</div>
)
}else{
return(<div></div>);
}
}
export default DishDetail;
Can somebody please explain why this piece of code is not working?
in debugger I found that isOpen attribute of modal is always false and is not changing on clicking the button
Actually your code works but the react component is not rerendered because react doesn't know something has changed, that's why you have to use an useState hook.
that doesn't change the code much, just put the isModalOpen state at the top of the function
const [isModalOpen, setisModalOpen] = useState(false);
const toggleModal = () => {
setisModalOpen(!isModalOpen);
console.log(isModalOpen);
}

Resources