I have 20 buttons and I wanted to apply class .active on the button which is clicked and the rest will inactive. Suppose I clicked on button one then I want to add an active class to button one and then when I clicked on button two then button two will get an active class and active class removed from button one.
import React from "react";
const PaginationButtonsList = (props) => {
const handleClick = (event) =>{
}
return (
<div className="pagination-buttons-list">
<button onClick={handleClick} id="button-1">1</button>
<button onClick={handleClick} id="button-2">2</button>
<button onClick={handleClick} id="button-3">3</button>
<button onClick={handleClick} id="button-4">4</button>
<button onClick={handleClick} id="button-5">5</button>
<button onClick={handleClick} id="button-6">6</button>
<button onClick={handleClick} id="button-7">7</button>
<button onClick={handleClick} id="button-8">8</button>
<button onClick={handleClick} id="button-9">9</button>
<button onClick={handleClick} id="button-10">10</button>
<button onClick={handleClick} id="button-11">11</button>
<button onClick={handleClick} id="button-12">12</button>
<button onClick={handleClick} id="button-13">13</button>
<button onClick={handleClick} id="button-14">14</button>
<button onClick={handleClick} id="button-15">15</button>
<button onClick={handleClick} id="button-16">16</button>
<button onClick={handleClick} id="button-17">17</button>
<button onClick={handleClick} id="button-18">18</button>
<button onClick={handleClick} id="button-19">19</button>
<button onClick={handleClick} id="button-20">20</button>
</div>
);
};
export { PaginationButtonsList };
I assume that you don't want a button with just generic numbers for text. So you will need to:
create an array list with all text that you want to set to the button
Then render all of it through the map and bind the onClick event to take the index
on click you should set that index in state and check which button
has that index so set it to active
.
import React, {useState} from "react";
/* Change this number to any text and add as many as you need */
let buttonText = ['1','2','3','4','5']
const PaginationButtonsList = (props) => {
const [activeIndex, setActiveIndex] = useState(-1)
const handleClick = (value) =>{
setActiveIndex(value)
}
return (
<div className="pagination-buttons-list">
{buttonText.map((text,index)=> (
<button onClick={()=>handleClick(index)} class={index === activeIndex ? "active" :""} id={`button-${index}`}>{text}</button>
)
</div>
);
};
export { PaginationButtonsList };
One way of approaching this would be to create an array of button objects that you can use to configure your component. Each button object in the array would have the shape { id: number, text: string, active: boolean } that defines it. You can that add that configuration to state.
When a button is clicked you reset the active values of each button (by updating a deep-copy the current state), update the active value of the clicked button, and finally create a new state with the updated data. That new state will be reflected in the component when it's re-rendered.
This method also has the advantages that 1) you encapsulate the button config in one place without the need for separate states, and 2) you don't need to hard-code all the buttons in the JSX - you can map over the button configuration to create an array of buttons using a useful Button component.
const { useState } = React;
// Pass in the button config
function Example({ btnConfig }) {
// Set state with the config
const [ btns, setBtns ] = useState(btnConfig);
// When a button is clicked grab its id from its dataset,
// make a deep copy of the state resetting all of the active
// values for each button to false, find the index of the button
// that was clicked, and then set its active value to true.
// Finally update the state to re-render the component
function handleClick(e) {
const { id } = e.target.dataset;
const reset = btns.map(btn => ({ ...btn, active: false }));
const index = reset.findIndex(btn => btn.id === +id);
reset[index].active = true;
setBtns(reset);
}
// `map` over the state and create JSX using a
// Button component passing down the properties from
// the objects in state as well as a reference to the
// `handleClick` function
return (
<div>
{btns.map(btn => {
const { id, text, active } = btn;
return (
<Button
key={id}
id={id}
active={active}
text={text}
handleClick={handleClick}
/>
);
})}
</div>
);
}
// Accepts the button props and returns a button. If
// the active value is true then apply the "active" class
function Button({ id, text, active, handleClick }) {
return (
<button
data-id={id}
onClick={handleClick}
className={active && 'active'}
>{text}
</button>
);
}
// Create a button config - an array of button of objects
const btnConfig = Array.from({length: 10}, (_, i) => {
const id = i + 1;
return { id, text: id, active: false };
});
// Pass in the button config to the component
ReactDOM.render(
<Example btnConfig={btnConfig} />,
document.getElementById('react')
);
button { margin-right: 0.5em; font-size: 1.2em; border-radius: 5px; padding: 0 0.4em; }
button:hover { cursor: pointer; background-color: #cdcdcd; }
button.active { background-color: lightgreen; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
You only need to save a single integer of state, the index corresponding to the active button -
function App({ buttons = [] }) {
const [active, setActive] = React.useState(-1)
const toggle = index => event => setActive(index)
return <div>
{buttons.map((b, key) =>
<button
className={active == key && 'active'}
onClick={toggle(key)}
children={b}
/>
)}
</div>
}
ReactDOM.render(
<App buttons={["🍟","🥨","🍐","🌮","🥤"]} />,
document.body
)
button { margin-right: 0.5em; font-size: 1.2em; border-radius: 5px; padding: 0 0.4em; }
button:hover { cursor: pointer; background-color: #cdcdcd; }
button.active { background-color: lightgreen; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
If you want repeated clicks to the same button to toggle the active off, if the same button is clicked twice, you can restore the initial active state of -1 -
function App({ buttons = [] }) {
const [active, setActive] = React.useState(-1)
const toggle = index => event =>
setActive(index == active ? -1 : index) // <-
return <div>
{buttons.map((b, key) =>
<button
className={active == key && 'active'}
onClick={toggle(key)}
children={b}
/>
)}
</div>
}
ReactDOM.render(
<App buttons={["🍟","🥨","🍐","🌮","🥤"]} />,
document.body
)
button { margin-right: 0.5em; font-size: 1.2em; border-radius: 5px; padding: 0 0.4em; }
button:hover { cursor: pointer; background-color: #cdcdcd; }
button.active { background-color: lightgreen; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
You can create an array state holding information for each button.
In each button state object in the array, include a property for whether the button is active or not. Then use this property when mapping the button states to actual buttons and set the active class if the button's state is active.
When a button is clicked, update the state array: make that button's state active and make every other button's state inactive.
Here's a complete example with types:
import {default as React, type ReactElement, useState} from 'react';
type ButtonState = {
active: boolean;
id: number;
};
const PaginationButtonsList = () => {
const [buttonStates, setButtonStates] = useState<ButtonState[]>(Array.from(
{length: 20},
(_, i) => ({id: i + 1, active: false}),
));
const createButtonFromState = (
{active, id}: ButtonState,
index: number,
): ReactElement => {
const setActiveExclusive = () => {
setButtonStates(arr => arr.map((state, i) => ({
...state,
active: i === index,
})));
};
const buttonProps = {
className: active ? 'active' : '',
id: `button-${id}`,
key: id,
onClick: setActiveExclusive,
};
return (<button {...buttonProps}>{id}</button>);
};
return (
<div className="pagination-buttons-list">
{buttonStates.map(createButtonFromState)}
</div>
);
};
Code in the TypeScript Playground
I'm trying to implement a feature to close a menu component when clicking outside of it. To achieve this I check if current target is present in ref node. The problem is when I click on Icon component... Inspecting it, e.target happens to be img from Icon component, and if I search it on ref.current, it's not present... Is there a way to link parent and child nodes together to achieve this condition ref.current.contains(e.target) when i click on a child component?
Parent component:
function Menu ({showMenu, close}) {
const ref = useRef(null)
useEffect(() => {
document.addEventListener('click', handleClickOutside)
return () =>{
document.removeEventListener('click', handleClickOutside)
}
}, [])
function handleClickOutside(e) {
if (ref.current && !ref.current.contains(e.target) && showMenu) {
close()
}
}
return (
<div ref={ref}>
<Icon action={openMenu2}/>
<h1>Menu</h1>
</div>
)
}
Child
function Icon ({action}) {
return (
<div onClick={() => action()}>
<i>
<img src={imageSrc} alt="icon"></img>
</i>
</div>
)
}
if u just want to use child Component's ref , u can pass ref to props.action
//Child
const cRef = useRef(null)
function Icon ({action}) {
return (
<div ref= onClick={() => action(cRef)}>
<i>
<img src={imageSrc} alt="icon"></img>
</i>
</div>
)
}
then u can use it in parent Component
or u can move those logic to child component
To achieve this I check if current target is present in ref node. The problem is when I click on Icon component... Inspecting it, e.target happens to be img from Icon component, and if I search it on ref.current, it's not present...
You can pass menu toggle function directly to down children to children,
Toggle Function
With this approach you don't need to check if showMenu is true because
this function will close the menu if it is open, and it will open if it is close
Assuming your state is at the parent of Menu component
const toggleMenu = () => {
setMenuOpen(!menuOpen);
};
Then in Menu component pass menuOpen as menu's state and toggleMenu as function to change it.
function Menu({ toggleMenu, menuOpen }) {
return (
<div style={{ display: "flex", alignItems: "center" }}>
<Icon toggleMenu={toggleMenu} />
<h1>Menu : {`${menuOpen ? "open" : "closed"} in Menu component`}</h1>
</div>
);
}
And in Icon component you can toggle the menu
function Icon({ toggleMenu }) {
return (
<div onClick={toggleMenu}>
<img
style={{ width: 35, cursor: "pointer" }}
alt="hamburger-menu"
src="https://cdn4.iconfinder.com/data/icons/wirecons-free-vector-icons/32/menu-alt-512.png"
/>
</div>
);
}
export default Icon;
In action on codesandbox :https://codesandbox.io/s/eager-joliot-zb3t7?file=/src/Menu.jsx:54-299
If your app is getting complicated with passing states and passing state change functions I recommend you to check redux pattern.
Here link for redux : https://react-redux.js.org/
I am trying to emulate a behavior similar to clicking on the overlay when a Modal popup is open. When clicking outside the sidenav component, I want to close all elements that are currently in a flyout mode.
I have a multi-tier nested navigation menu that is stored in its own component, Sidebar. I have the following piece of code that handles clicks that occur outside the Sidebar component:
class Sidebar extends React.Component {
...
handleClick = (e) => {
if (this.node.contains(e.target)) {
return;
}
console.log('outside');
};
componentDidMount() {
window.addEventListener('mousedown', this.handleClick, false);
}
componentWillUnmount() {
window.removeEventListener('mousedown', this.handleClick, false);
}
render() {
return (
<div
ref={node => this.node = node}
className="sidebar"
data-color={this.props.bgColor}
data-active-color={this.props.activeColor}
>
{renderSideBar()}
</div>
);
}
...
}
This part works fine - but when the flyout menus get displayed on clicking a parent menu option, I would like it to close -any- flyout menus that are currently opened.
-|
|
- Menu Item 1
|
|-option 1 (currently open)
|-option 2
- Menu Item 2
|
|-option 1 (closed)
|-option 2 (closed, clicked to expand - this is when it should close [Menu Item 1/Option 1]
The menu items are generated using <li> tags when mapping the data object containing the menu structure.
Is there a way to basically select all registered objects that have the class of 'collapse' / aria-expanded="true" and remove it? Similar to how jQuery would select dom elements and manipulate them.
I know that this is not the premise in which React works, it is just an example of the behavior I want to emulate.
As far as I understand you want to modify the DOM subtree from another component. To achive your goal you can use ref.
Using ref is helpful when you want to access HtmlElement API directly - in my example I use animate(). Please, read the documentation as it describes more of ref use cases.
Below is the simple example of animating <Sidebar/> shrinking when user clicks on <Content />.
const { useRef } = React;
function Main() {
const sidebar = useRef(null);
const handleClick = () => {
sidebar.current.hide();
};
return (
<div className="main">
<Sidebar ref={sidebar} />
<Content onClick={handleClick} />
</div>
);
}
class Sidebar extends React.Component {
constructor(props) {
super(props);
this.state = { visible: true };
this.show = this.show.bind(this);
this.sidebar = React.createRef(null);
}
show() {
if (!this.state.visible) {
this.sidebar.current.animate(
{ flex: [1, 2], "background-color": ["teal", "red"] },
300
);
this.setState({ visible: true });
}
}
hide() {
if (this.state.visible) {
this.sidebar.current.animate(
{ flex: [2, 1], "background-color": ["red", "teal"] },
300
);
this.setState({ visible: false });
}
}
render() {
return (
<div
ref={this.sidebar}
className={this.state.visible ? "sidebar--visible" : "sidebar"}
onClick={this.show}
>
Sidebar
</div>
);
}
}
function Content({ onClick }) {
return (
<div className="content" onClick={onClick}>
Content
</div>
);
}
ReactDOM.render(<Main />, document.getElementById("root"));
.main {
display: flex;
height: 100vh;
}
.sidebar {
flex: 1;
background-color: teal;
}
.sidebar--visible {
flex: 2;
background-color: red;
}
.content {
flex: 7;
background-color: beige;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
So I have a SideDrawer that I'm rendering like this in the root App component:
render() {
const { isOpen } = this.props;
return (
<BrowserRouter>
<SideDrawer />
{/* isOpen && <SideDrawer /> */}
<Routes ..../>
</BrowserRouter>
);
}
}
This is the reducer:
export const drawer = (state = initialState, { type, payload }) => {
switch (type) {
case CLOSE_DRAWER:
return { ...state, isOpen: false };
case OPEN_DRAWER:
return { isOpen: true, movieId: payload };
default:
return state;
}
};
And In the SideDrawer component, I was using the state of the drawer and css to handle the transition:
export const SideDrawer = ({ isOpen, closeDrawer, movieId }) => {
const drawerClass = cx({
container: true,
open: isOpen,
});
return (
<div className={drawerClass}>
<button className={styles.button} onClick={closeDrawer}>
<img src={backButton} alt={text.alt} />
</button>
<MovieBanner movieId={movieId} />
</div>
);
};
Now, my mentor wants me to render the SideDrawer conditionally. If isOpen is true, then render the SideDrawer. However, the problem is that the transition is not going to work, because I'd only be rendering the SideDrawer when the state of isOpen is true. The only way it's working now is if I just render it all the time on the App component so I can keep track of the state and add my CSS transition when the state changes from false to true
My mentor mentioned to only render the SideDrawer if the SideDrawer is open, but I need to have it rendered to know the previous state of it no?
When an element is removed from the DOM, it will no longer be shown to the user. This also means transitions on it will have no impact.
If you would like to use transitions, keep the element in the DOM at least until the transitions have finished, or always. Here is a demo of two <div>s, first one is always in the DOM, the second one only when sidebarOn is true:
function Demo() {
const [sidebarOn, setSidebarOn] = React.useState(false)
const toggleSidebar = () => setSidebarOn(!sidebarOn)
return (
<div>
<button onClick={toggleSidebar}>toggle</button>
<div className={'sidebar ' + sidebarOn}>always rendered</div>
{sidebarOn &&
<div className={'sidebar ' + sidebarOn}>only rendered when on</div>
}
</div>
)
}
ReactDOM.render(<Demo />, document.getElementById('root'))
.sidebar {
background-color: yellow;
opacity: 0;
transition-property: opacity;
transition-duration: 500ms;
}
.sidebar.true {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<div id="root"></div>
There exists a transitionend event, which you could use to remove the element once the transition is over, but support in browsers is not widespread enough at this time.
I am messing around with React.js for the first time and cannot find a way to show or hide something on a page via click event. I am not loading any other library to the page, so I am looking for some native way using the React library. This is what I have so far. I would like to show the results div when the click event fires.
var Search= React.createClass({
handleClick: function (event) {
console.log(this.prop);
},
render: function () {
return (
<div className="date-range">
<input type="submit" value="Search" onClick={this.handleClick} />
</div>
);
}
});
var Results = React.createClass({
render: function () {
return (
<div id="results" className="search-results">
Some Results
</div>
);
}
});
React.renderComponent(<Search /> , document.body);
React circa 2020
In the onClick callback, call the state hook's setter function to update the state and re-render:
const Search = () => {
const [showResults, setShowResults] = React.useState(false)
const onClick = () => setShowResults(true)
return (
<div>
<input type="submit" value="Search" onClick={onClick} />
{ showResults ? <Results /> : null }
</div>
)
}
const Results = () => (
<div id="results" className="search-results">
Some Results
</div>
)
ReactDOM.render(<Search />, document.querySelector("#container"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
JSFiddle
React circa 2014
The key is to update the state of the component in the click handler using setState. When the state changes get applied, the render method gets called again with the new state:
var Search = React.createClass({
getInitialState: function() {
return { showResults: false };
},
onClick: function() {
this.setState({ showResults: true });
},
render: function() {
return (
<div>
<input type="submit" value="Search" onClick={this.onClick} />
{ this.state.showResults ? <Results /> : null }
</div>
);
}
});
var Results = React.createClass({
render: function() {
return (
<div id="results" className="search-results">
Some Results
</div>
);
}
});
ReactDOM.render( <Search /> , document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
JSFiddle
<style type="text/css">
.hidden { display:none; }
</style>
const Example = props =>
<div className={props.shouldHide? 'hidden' : undefined}>Hello</div>
Here is an alternative syntax for the ternary operator:
{ this.state.showMyComponent ? <MyComponent /> : null }
is equivalent to:
{ this.state.showMyComponent && <MyComponent /> }
Learn why
Also alternative syntax with display: 'none';
<MyComponent style={this.state.showMyComponent ? {} : { display: 'none' }} />
However, if you overuse display: 'none', this leads to DOM pollution and ultimately slows down your application.
Here is my approach.
import React, { useState } from 'react';
function ToggleBox({ title, children }) {
const [isOpened, setIsOpened] = useState(false);
function toggle() {
setIsOpened(wasOpened => !wasOpened);
}
return (
<div className="box">
<div className="boxTitle" onClick={toggle}>
{title}
</div>
{isOpened && (
<div className="boxContent">
{children}
</div>
)}
</div>
);
}
In code above, to achieve this, I'm using code like:
{opened && <SomeElement />}
That will render SomeElement only if opened is true. It works because of the way how JavaScript resolve logical conditions:
true && true && 2; // will output 2
true && false && 2; // will output false
true && 'some string'; // will output 'some string'
opened && <SomeElement />; // will output SomeElement if `opened` is true, will output false otherwise (and false will be ignored by react during rendering)
// be careful with 'falsy' values eg
const someValue = [];
someValue.length && <SomeElement /> // will output 0, which will be rednered by react
// it'll be better to:
someValue.length > 0 && <SomeElement /> // will render nothing as we cast the value to boolean
Reasons for using this approach instead of CSS 'display: none';
While it might be 'cheaper' to hide an element with CSS - in such case 'hidden' element is still 'alive' in react world (which might make it actually way more expensive)
it means that if props of the parent element (eg. <TabView>) will change - even if you see only one tab, all 5 tabs will get re-rendered
the hidden element might still have some lifecycle methods running - eg. it might fetch some data from the server after every update even tho it's not visible
the hidden element might crash the app if it'll receive incorrect data. It might happen as you can 'forget' about invisible nodes when updating the state
you might by mistake set wrong 'display' style when making element visible - eg. some div is 'display: flex' by default, but you'll set 'display: block' by mistake with display: invisible ? 'block' : 'none' which might break the layout
using someBoolean && <SomeNode /> is very simple to understand and reason about, especially if your logic related to displaying something or not gets complex
in many cases, you want to 'reset' element state when it re-appears. eg. you might have a slider that you want to set to initial position every time it's shown. (if that's desired behavior to keep previous element state, even if it's hidden, which IMO is rare - I'd indeed consider using CSS if remembering this state in a different way would be complicated)
with the newest version react 0.11 you can also just return null to have no content rendered.
Rendering to null
This is a nice way to make use of the virtual DOM:
class Toggle extends React.Component {
state = {
show: true,
}
toggle = () => this.setState((currentState) => ({show: !currentState.show}));
render() {
return (
<div>
<button onClick={this.toggle}>
toggle: {this.state.show ? 'show' : 'hide'}
</button>
{this.state.show && <div>Hi there</div>}
</div>
);
}
}
Example here
Using React hooks:
const Toggle = () => {
const [show, toggleShow] = React.useState(true);
return (
<div>
<button
onClick={() => toggleShow(!show)}
>
toggle: {show ? 'show' : 'hide'}
</button>
{show && <div>Hi there</div>}
</div>
)
}
Example here
I created a small component that handles this for you: react-toggle-display
It sets the style attribute to display: none !important based on the hide or show props.
Example usage:
var ToggleDisplay = require('react-toggle-display');
var Search = React.createClass({
getInitialState: function() {
return { showResults: false };
},
onClick: function() {
this.setState({ showResults: true });
},
render: function() {
return (
<div>
<input type="submit" value="Search" onClick={this.onClick} />
<ToggleDisplay show={this.state.showResults}>
<Results />
</ToggleDisplay>
</div>
);
}
});
var Results = React.createClass({
render: function() {
return (
<div id="results" className="search-results">
Some Results
</div>
);
}
});
React.renderComponent(<Search />, document.body);
There are several great answers already, but I don't think they've been explained very well and several of the methods given contain some gotchas that might trip people up. So I'm going to go over the three main ways (plus one off-topic option) to do this and explain the pros and cons. I'm mostly writing this because Option 1 was recommended a lot and there's a lot of potential issues with that option if not used correctly.
Option 1: Conditional Rendering in the parent.
I don't like this method unless you're only going to render the component one time and leave it there. The issue is it will cause react to create the component from scratch every time you toggle the visibility.
Here's the example. LogoutButton or LoginButton are being conditionally rendered in the parent LoginControl. If you run this you'll notice the constructor is getting called on each button click. https://codepen.io/Kelnor/pen/LzPdpN?editors=1111
class LoginControl extends React.Component {
constructor(props) {
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = {isLoggedIn: false};
}
handleLoginClick() {
this.setState({isLoggedIn: true});
}
handleLogoutClick() {
this.setState({isLoggedIn: false});
}
render() {
const isLoggedIn = this.state.isLoggedIn;
let button = null;
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
}
}
class LogoutButton extends React.Component{
constructor(props, context){
super(props, context)
console.log('created logout button');
}
render(){
return (
<button onClick={this.props.onClick}>
Logout
</button>
);
}
}
class LoginButton extends React.Component{
constructor(props, context){
super(props, context)
console.log('created login button');
}
render(){
return (
<button onClick={this.props.onClick}>
Login
</button>
);
}
}
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
ReactDOM.render(
<LoginControl />,
document.getElementById('root')
);
Now React is pretty quick at creating components from scratch. However, it still has to call your code when creating it. So if your constructor, componentDidMount, render, etc code is expensive, then it'll significantly slow down showing the component. It also means you cannot use this with stateful components where you want the state to be preserved when hidden (and restored when displayed.) The one advantage is that the hidden component isn't created at all until it's selected. So hidden components won't delay your initial page load. There may also be cases where you WANT a stateful component to reset when toggled. In which case this is your best option.
Option 2: Conditional Rendering in the child
This creates both components once. Then short circuits the rest of the render code if the component is hidden. You can also short circuit other logic in other methods using the visible prop. Notice the console.log in the codepen page. https://codepen.io/Kelnor/pen/YrKaWZ?editors=0011
class LoginControl extends React.Component {
constructor(props) {
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = {isLoggedIn: false};
}
handleLoginClick() {
this.setState({isLoggedIn: true});
}
handleLogoutClick() {
this.setState({isLoggedIn: false});
}
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
<LoginButton isLoggedIn={isLoggedIn} onClick={this.handleLoginClick}/>
<LogoutButton isLoggedIn={isLoggedIn} onClick={this.handleLogoutClick}/>
</div>
);
}
}
class LogoutButton extends React.Component{
constructor(props, context){
super(props, context)
console.log('created logout button');
}
render(){
if(!this.props.isLoggedIn){
return null;
}
return (
<button onClick={this.props.onClick}>
Logout
</button>
);
}
}
class LoginButton extends React.Component{
constructor(props, context){
super(props, context)
console.log('created login button');
}
render(){
if(this.props.isLoggedIn){
return null;
}
return (
<button onClick={this.props.onClick}>
Login
</button>
);
}
}
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
ReactDOM.render(
<LoginControl />,
document.getElementById('root')
);
Now, if the initialization logic is quick and the children are stateless, then you won't see a difference in performance or functionality. However, why make React create a brand new component every toggle anyway? If the initialization is expensive however, Option 1 will run it every time you toggle a component which will slow the page down when switching. Option 2 will run all of the component's inits on first page load. Slowing down that first load. Should note again. If you're just showing the component one time based on a condition and not toggling it, or you want it to reset when toggledm, then Option 1 is fine and probably the best option.
If slow page load is a problem however, it means you've got expensive code in a lifecycle method and that's generally not a good idea. You can, and probably should, solve the slow page load by moving the expensive code out of the lifecycle methods. Move it to an async function that's kicked off by ComponentDidMount and have the callback put it in a state variable with setState(). If the state variable is null and the component is visible then have the render function return a placeholder. Otherwise render the data. That way the page will load quickly and populate the tabs as they load. You can also move the logic into the parent and push the results to the children as props. That way you can prioritize which tabs get loaded first. Or cache the results and only run the logic the first time a component is shown.
Option 3: Class Hiding
Class hiding is probably the easiest to implement. As mentioned you just create a CSS class with display: none and assign the class based on prop. The downside is the entire code of every hidden component is called and all hidden components are attached to the DOM. (Option 1 doesn't create the hidden components at all. And Option 2 short circuits unnecessary code when the component is hidden and removes the component from the DOM completely.) It appears this is faster at toggling visibility according some tests done by commenters on other answers but I can't speak to that.
Option 4: One component but change Props. Or maybe no component at all and cache HTML.
This one won't work for every application and it's off topic because it's not about hiding components, but it might be a better solution for some use cases than hiding. Let's say you have tabs. It might be possible to write one React Component and just use the props to change what's displayed in the tab. You could also save the JSX to state variables and use a prop to decide which JSX to return in the render function. If the JSX has to be generated then do it and cache it in the parent and send the correct one as a prop. Or generate in the child and cache it in the child's state and use props to select the active one.
You set a boolean value in the state (e.g. 'show)', and then do:
var style = {};
if (!this.state.show) {
style.display = 'none'
}
return <div style={style}>...</div>
A simple method to show/hide elements in React using Hooks
const [showText, setShowText] = useState(false);
Now, let's add some logic to our render method:
{showText && <div>This text will show!</div>}
And
onClick={() => setShowText(!showText)}
Good job.
I was able to use css property "hidden". Don't know about possible drawbacks.
export default function App() {
const [hidden, setHidden] = useState(false);
return (
<div>
<button onClick={() => setHidden(!hidden)}>HIDE</button>
<div hidden={hidden}>hidden component</div>
</div>
);
}
Best practice is below according to the documentation:
{this.state.showFooter && <Footer />}
Render the element only when the state is valid.
Simple hide/show example with React Hooks: (srry about no fiddle)
const Example = () => {
const [show, setShow] = useState(false);
return (
<div>
<p>Show state: {show}</p>
{show ? (
<p>You can see me!</p>
) : null}
<button onClick={() => setShow(!show)}>
</div>
);
};
export default Example;
class FormPage extends React.Component{
constructor(props){
super(props);
this.state = {
hidediv: false
}
}
handleClick = (){
this.setState({
hidediv: true
});
}
render(){
return(
<div>
<div className="date-range" hidden = {this.state.hidediv}>
<input type="submit" value="Search" onClick={this.handleClick} />
</div>
<div id="results" className="search-results" hidden = {!this.state.hidediv}>
Some Results
</div>
</div>
);
}
}
I start with this statement from the React team:
In React, you can create distinct components that encapsulate behaviour
you need. Then, you can render only some of them, depending on the
state of your application.
Conditional rendering in React works the same way conditions work in
JavaScript. Use JavaScript operators like if or the conditional
operator to create elements representing the current state, and let
React update the UI to match them.
You basically need to show the component when the button gets clicked, you can do it two ways, using pure React or using CSS, using pure React way, you can do something like below code in your case, so in the first run, results are not showing as hideResults is true, but by clicking on the button, state gonna change and hideResults is false and the component get rendered again with the new value conditions, this is very common use of changing component view in React...
var Search = React.createClass({
getInitialState: function() {
return { hideResults: true };
},
handleClick: function() {
this.setState({ hideResults: false });
},
render: function() {
return (
<div>
<input type="submit" value="Search" onClick={this.handleClick} />
{ !this.state.hideResults && <Results /> }
</div> );
}
});
var Results = React.createClass({
render: function() {
return (
<div id="results" className="search-results">
Some Results
</div>);
}
});
ReactDOM.render(<Search />, document.body);
If you want to do further study in conditional rendering in React, have a look here.
class Toggle extends React.Component {
state = {
show: true,
}
render() {
const {show} = this.state;
return (
<div>
<button onClick={()=> this.setState({show: !show })}>
toggle: {show ? 'show' : 'hide'}
</button>
{show && <div>Hi there</div>}
</div>
);
}
}
If you would like to see how to TOGGLE the display of a component checkout this fiddle.
http://jsfiddle.net/mnoster/kb3gN/16387/
var Search = React.createClass({
getInitialState: function() {
return {
shouldHide:false
};
},
onClick: function() {
console.log("onclick");
if(!this.state.shouldHide){
this.setState({
shouldHide: true
})
}else{
this.setState({
shouldHide: false
})
}
},
render: function() {
return (
<div>
<button onClick={this.onClick}>click me</button>
<p className={this.state.shouldHide ? 'hidden' : ''} >yoyoyoyoyo</p>
</div>
);
}
});
ReactDOM.render( <Search /> , document.getElementById('container'));
Use ref and manipulate CSS
One way could be to use React's ref and manipulate CSS class using the browser's API. Its benefit is to avoid rerendering in React if the sole purpose is to hide/show some DOM element on the click of a button.
// Parent.jsx
import React, { Component } from 'react'
export default class Parent extends Component {
constructor () {
this.childContainer = React.createRef()
}
toggleChild = () => {
this.childContainer.current.classList.toggle('hidden')
}
render () {
return (
...
<button onClick={this.toggleChild}>Toggle Child</button>
<div ref={this.childContainer}>
<SomeChildComponent/>
</div>
...
);
}
}
// styles.css
.hidden {
display: none;
}
PS Correct me if I am wrong. :)
In some cases higher order component might be useful:
Create higher order component:
export var HidableComponent = (ComposedComponent) => class extends React.Component {
render() {
if ((this.props.shouldHide!=null && this.props.shouldHide()) || this.props.hidden)
return null;
return <ComposedComponent {...this.props} />;
}
};
Extend your own component:
export const MyComp= HidableComponent(MyCompBasic);
Then you can use it like this:
<MyComp hidden={true} ... />
<MyComp shouldHide={this.props.useSomeFunctionHere} ... />
This reduces a bit boilerplate and enforces sticking to naming conventions, however please be aware of that MyComp will still be instantiated - the way to omit is was mentioned earlier:
{ !hidden && <MyComp ... /> }
If you use bootstrap 4, you can hide element that way
className={this.state.hideElement ? "invisible" : "visible"}
Use rc-if-else module
npm install --save rc-if-else
import React from 'react';
import { If } from 'rc-if-else';
class App extends React.Component {
render() {
return (
<If condition={this.props.showResult}>
Some Results
</If>
);
}
}
Use this lean and short syntax:
{ this.state.show && <MyCustomComponent /> }
Here comes the simple, effective and best solution with a Classless React Component for show/hide the elements. Use of React-Hooks which is available in the latest create-react-app project that uses React 16
import React, {useState} from 'react';
function RenderPara(){
const [showDetail,setShowDetail] = useState(false);
const handleToggle = () => setShowDetail(!showDetail);
return (
<React.Fragment>
<h3>
Hiding some stuffs
</h3>
<button onClick={handleToggle}>Toggle View</button>
{showDetail && <p>
There are lot of other stuffs too
</p>}
</React.Fragment>)
}
export default RenderPara;
Happy Coding :)
//use ternary condition
{ this.state.yourState ? <MyComponent /> : null }
{ this.state.yourState && <MyComponent /> }
{ this.state.yourState == 'string' ? <MyComponent /> : ''}
{ this.state.yourState == 'string' && <MyComponent /> }
//Normal condition
if(this.state.yourState){
return <MyComponent />
}else{
return null;
}
<button onClick={()=>this.setState({yourState: !this.props.yourState}>Toggle View</button>
Just figure out a new and magic way with using(useReducer) for functional components
const [state, handleChangeState] = useReducer((state) => !state, false);
change state
This can also be achieved like this (very easy way)
class app extends Component {
state = {
show: false
};
toggle= () => {
var res = this.state.show;
this.setState({ show: !res });
};
render() {
return(
<button onClick={ this.toggle }> Toggle </button>
{
this.state.show ? (<div> HELLO </div>) : null
}
);
}
this example shows how you can switch between components by using a toggle which switches after every 1sec
import React ,{Fragment,Component} from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const Component1 = () =>(
<div>
<img
src="https://i.pinimg.com/originals/58/df/1d/58df1d8bf372ade04781b8d4b2549ee6.jpg" />
</div>
)
const Component2 = () => {
return (
<div>
<img
src="http://www.chinabuddhismencyclopedia.com/en/images/thumb/2/2e/12ccse.jpg/250px-
12ccse.jpg" />
</div>
)
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
toggleFlag:false
}
}
timer=()=> {
this.setState({toggleFlag:!this.state.toggleFlag})
}
componentDidMount() {
setInterval(this.timer, 1000);
}
render(){
let { toggleFlag} = this.state
return (
<Fragment>
{toggleFlag ? <Component1 /> : <Component2 />}
</Fragment>
)
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
The application of states and effects has and must be encapsulated in the same component, for this reason, there is nothing better than creating a custom component as a hook to solve in this case whether to make particular blocks or elements visible or invisible.
// hooks/useOnScreen.js
import { useState, useEffect } from "react"
const useOnScreen = (ref, rootMargin = "0px") => {
const [isVisible, setIsVisible] = useState(false)
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
setIsVisible(entry.isIntersecting)
},
{
rootMargin
}
);
const currentElement = ref?.current
if (currentElement) {
observer.observe(currentElement)
}
return () => {
observer.unobserve(currentElement)
}
}, [])
return isVisible
}
export default useOnScreen
Then the custom hook is embedded inside the component
import React, { useRef } from "react";
import useOnScreen from "hooks/useOnScreen";
const MyPage = () => {
const ref = useRef(null)
const isVisible = useOnScreen(ref)
const onClick = () => {
console.log("isVisible", isVisible)
}
return (
<div ref={ref}>
<p isVisible={isVisible}>
Something is visible
</p>
<a
href="#"
onClick={(e) => {
e.preventDefault();
onClick(onClick)
}}
>
Review
</a>
</div>
)
}
export default MyPage
The ref variable, controlled by the useRef hook, allows us to capture the location in the DOM of the block that we want to control, then the isVisible variable, controlled by the useOnScreen hook, allows us to make the inside the block I signal by the useRef hook.
I believe that this implementation of the useState, useEfect, and useRef hooks allows you to avoid component rendering by separating them using custom hooks.
Hoping that this knowledge will be of use to you.
It is very simple to hide and show the elements in react.
There are multiple ways but I will show you two.
Way 1:
const [isVisible, setVisible] = useState(false)
let onHideShowClick = () =>{
setVisible(!isVisible)
}
return (<div>
<Button onClick={onHideShowClick} >Hide/Show</Button>
{(isVisible) ? <p>Hello World</p> : ""}
</div>)
Way 2:
const [isVisible, setVisible] = useState(false)
let onHideShowClick = () =>{
setVisible(!isVisible)
}
return (<div>
<Button onClick={onHideShowClick} >Hide/Show</Button>
<p style={{display: (isVisible) ? 'block' : 'none'}}>Hello World</p>
</div>)
It is just working like if and else.
In Way one, it will remove and re-render elements in Dom.
In the Second way you are just displaying elements as false or true.
Thank you.
You've to do the small change in the code for continuously hiding and showing
const onClick = () => {setShowResults(!showResults}
Problem will be solved
const Search = () => {
const [showResults, setShowResults] = React.useState(false)
const onClick = () => setShowResults(true)
const onClick = () => {setShowResults(!showResults}
return (
<div>
<input type="submit" value="Search" onClick={onClick} />
{ showResults ? <Results /> : null }
</div>
)
}
const Results = () => (
<div id="results" className="search-results">
Some Results
</div>
)
ReactDOM.render(<Search />, document.querySelector("#container"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
```