import React, {useState} from 'react'; import './App.css';
function App() {
const [flag, setflag] = useState(0);
const startCountdown = () => {
setflag(1);
};
return (
<>
<button onClick={startCountdown}>Start countdown</button>
{(() => {
if (flag===1){
console.log("INN");
<h1>Count Down Started</>
}
})}
</>
);
}
export default App;
Whenever the user clicks on the button, h1 tag which contains "Countdown Started" should be displayed on the screen. But, its not happening.
CodePudding user response:
Try it like this:
return (
<>
<button onClick={startCountdown}>Start countdown</button>
{flag === 1 && (
<h1>Count Down Started</h1>
)}
</>
)
CodePudding user response:
You could just add a conditional
to achieve this.
Sandbox link : https://codesandbox.io/s/react-hooks-counter-demo-forked-2qc1d?file=/src/index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [flag, setflag] = useState(0);
const startCountdown = () => {
setflag(1);
};
return (
<>
<button onClick={startCountdown}>Start countdown</button>
{flag === 1 && <h1>Count Down Started</h1>}
</>
);
}
export default App;
CodePudding user response:
Your function is never really run, it is just defined. Execute it using parentheses ()
. Also since you have curly braces you will have to use return
keyword inside the arrow function.
return (
<>
<button onClick={startCountdown}>Start countdown</button>
{(() => {
if (flag===1){
console.log("INN");
return <h1>Count Down Started</h1>
}
})()}
</>
);
CodePudding user response:
You can do with conditional rendering.
function App() {
const [flag, setflag] = useState(0);
const startCountdown = () => {
setflag(1);
};
return (
<>
<button onClick={startCountdown}>Start countdown</button>
{flag === 1 && <h1>Count Down Started</>}
</>
);
}
export default App;