This question already has answers here:
Show or hide element in React
(34 answers)
Closed 19 days ago.
I would like a text to be displayed on the screen and only be hidden when pressing a button, but I don't know how. I thought of using useState like this:
const [textVisibility, setTextVisibility] = useState(true)
<button onClick={() => setTextVisibility(false)} />
the problem I found is that when clicking on the button the page will be rendered again and the visibility value will be the default value (true). How can I do that?
const App(){
const [isVisible, setIsVisible] = useState(false)
return (
<>
{isVisible ? <label> This text will be shown on button click </label> : null
}
<button onClick={()=>setIsVisible(true)}>click to show </button>
</>
)
}
Idk what are you experiencing but for me it works fine the following code:
import React from 'react';
import {useState} from 'react';
export function App(props) {
const [textVisibility, setTextVisibility] = useState(true)
return (
<div className='App'>
{textVisibility && <h1 onClick={() => setTextVisibility(!textVisibility)}>Hello React.</h1>}
<button onClick={() => setTextVisibility(false)}>Invisible</button>
<button onClick={() => setTextVisibility(true)}>Visible</button>
</div>
);
}
Related
I would like to explain my problem of the day
currently I use a modal works very well
so my problem and the next one
When I close my modal I correctly unmount the states,
logically i have an animation will have to be carried out during the closing, and the nothing, I have the impression that I disassemble my component too quickly
import React, { useState } from "react";
function Lead() {
const [isModalOpen, setModalOpen] = useState(false);
const handleDisplayModal = (value) => {
setModalOpen(value);
};
return (
<div>
{isModalOpen && (
<Modal
onClose={() => handleDisplayModal(false)}
isOpen={isModalOpen}
/>
)}
<Top
setModalOpen={setModalOpen}
/>
</div>
);
}
export default Lead;
I am open to any proposal thank you very much.
i'm new here. I got a problem with a task. I want a button that if you press it hides some content, a string in this case. If the content is hidden the button must change the text inside it,
and it must say "show" and instead of hiding it shows the content
previously hidden. If the content is already displayed, the button text will be "hide".
I don't understand how to use if statement
...
import React { useState } from "react";
function App() {
const [hideText, setHideText] = useState(false);
const onClick = () => setHideText(false);
return (
<div>
<button onClick={onClick}>Click me</button>
{hideText ? <Text /> : null}
</div>
);
}
const Text = () => <div>I will disappear, true Magic</div>;
export default App;
...
I don't know if I correctly understood your needs.
I changed the variable name to be more meaningful :)
Now the button shows Hide when the text is visible and Show when it's hidden. Clicking the button changes the state.
import React { useState } from "react";
function App() {
const [isTextHidden, setTextHidden] = useState(true);
const onClick = () => setTextHidden(!isTextHidden);
return (
<div>
<button onClick={onClick}>{isTextHidden ? 'Show' : 'Hide'}</button>
{!textHidden ? <Text /> : null}
</div>
);
}
const Text = () => <div>I will disappear, true Magic</div>;
export default App;
import React { useState } from "react";
function App() {
const [isVisible, setVisible] = useState(true);
const onClick = () => setVisible(!isVisible);
return (
<div>
<button onClick={onClick}>{isVisible? 'Hide' : 'Show'}</button>
{isVisible? <Text /> : null}
</div>
);
}
const Text = () => <div>I will disappear, true Magic</div>;
export default App;
const div_ref = useRef();
<div ref={div_ref} />
What are the properties of div_ref that I can use to find out if the mouse is hovering over div_ref?
You can use the onMouseEnter() listener in React to know when an element is being hovered with the mouse. For example, if you wanted to show a text in React when you hover over a heading (or any other element), you would use the following code:
import React, { useState } from 'react';
function App() {
const [visible, setVisible] = useState(false); // initiate it at false
return (
<div>
<h2
onMouseEnter={() => setVisible(true)}
onMouseLeave={() => setVisible(false)}>
Move Mouse Towards Me
</h2>
{visible && ( // you can use "&&" since there is no else in this case
<div>Text to show</div>
)}
</div>
);
}
export default App;
I am using the modal library winbox. It works well if use simple html and javascript. But I can't append a React node to it.
The modal has a html parameter, that accept an html string such as div.innerHTML = <div>hello</div> . The code source is: this.body.innerHTML = html;.
So adding a classic React element makes the modal crash. The only solution I found is to use react-dom's renderToString method: html: renderToString(children). But the component is not dynamic anymore (no state update, etc.).
I also tried to surround React.renderDOM by a div inside the modal and attach the component to it, as the app is attached to index.js's #root div.
html: <div id="modal">
{render(
<div children={content} />,
document.querySelector("#modal")
)},
</div>
My question is thus: how to pass a dynamic React component to the body of this modal?
Here is my code:
import React from "react";
import useModal from "./useModal";
const Counter = () => {
const [count, setCount] = useState(1);
return (
<div>
The count is {count}
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
};
export default function App() {
const [open, setOpen] = useState(false);
useModal(open, setOpen, <Counter />);
return (
<div id="#hi">
<button onClick={() => setOpen(!open)}>toggle</button>
</div>
);
}
// useModal
import WinBox from "winbox/src/js/winbox.js";
import "winbox/dist/css/winbox.min.css";
import React from "react";
import { render } from "react-dom";
export default function useModal(open, onToggle, content) {
const modal = open
? new WinBox({
title: "Hello",
max: true,
html: content, // INSERT DYNAMIC COMPONENT HERE
onclose: () => onToggle(false)
})
: null;
return modal;
}
Thank you!
You can use winbox-react package from npm. winbox-react npm link Example code is given below. Youcan use normal jsx as children of the WinboxReact component.
const Hero = () => {
const [show, setShow] = useState(false)
const clickHandeler = () => {
setShow(!show)
}
return (
<div className='text-center'>
{show && (
<WinboxReact
onClose={clickHandeler}
background='linear-gradient(90deg, rgba(49,36,239,1) 0%, rgba(67,0,168,1) 100%)'
><h1>Hello</h1></WinboxReact>
)}
<button onClick={clickHandeler} className='btn btn-custom btn-lg mt-4'>
Show Example
</button>
</div>
)
}
export default Hero
I have 2 buttons and 1 h1 I need to count how many times the button is clicked and display the button name with no. of count it clicked in h1 with the name of the button. Right now I am getting the name of button correctly but not able to display the click count for the button. please help
import React, { Component, Fragment } from 'react'
import ReactDOM from 'react-dom'
export default class App extends Component {
state={
button:"",
countClick:0
}
buttonClick=(e)=>{
e.preventDefault();
this.setState({button:e.target.name, countClick:this.state.countClick+1});
}
render() {
return (
<Fragment>
<h1>
{this.state.button} clicked {this.state.countClick} times
</h1>
<button name="Button 1" type="button" onClick={this.buttonClick}>Button 1</button>
<button name="Button 2" type="button" onClick={this.buttonClick}>Button 2</button>
</Fragment>
)
}
}
ReactDOM.render(<App />,document.getElementById('root'));
Thank You
Some notice points:
build an Array to store each button's click amount status.
optionally use {id, value} structure for the array items, since we need to display the clicked button with its click amount.
use map() to prevent from repeating yourself about <button />.
pass the identity index as a param inside the nested handler function.
Full code:
import React from "react";
import "./styles.css";
const amount = 2;
export default function App() {
const [clickList, setClickList] = React.useState(
[...Array(amount).keys()].map(x => ({ id: `Button ${x + 1}`, value: 0 }))
);
const [activeButton, setActiveButton] = React.useState("");
const buttonClick = idx => e => {
const result = [...clickList];
result[idx].value += 1;
setClickList(result);
setActiveButton(e.target.name);
};
return (
<>
<h1>
{`${activeButton} clicked ${clickList.find(x => x.id === activeButton)?.value ?? 0} times`}
</h1>
{clickList.map((x, idx) => (
<button name={x.id} type="button" onClick={buttonClick(idx)}>
{x.id}
</button>
))}
</>
);
}
setState can take an object or a callback with previous state as parameter.
Change your setState like this:
this.setState(prevState => ({button:e.target.name, countClick: prevState + 1}));