Show or Hide Element in React

Show or hide element in React

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>

React: hiding vs removing components

Let's compare some of the differences between these two methods for toggling HTML element visibility, element toggling (aka display: none|block) and JSX short circuit rendering

  1. Simplicity - As you know JSX has been optimised for reactively toggling markup, so it will not print false, true, null and undefined, hence you can write shorter logics in there. Similar case for not using template literals instead of JSX was brought by Facebook https://facebook.github.io/jsx/#why-not-template-literals. Simplicity leads to maintainability, in the long run it will help your app not become another spaghetti nonsense.
  isShown && <div />

vs

 <div style={{ display: isShown ? 'block' : 'none' }} />

  1. Performance - Spanning way more nodes is never good for performance and memory usage, generally it varies per application. It can be benchmarked using Chrome's Performance Monitor or the React Profiler. But more importantly React builds new performance optimisations around the knowledge that you would follow https://reactjs.org/docs/jsx-in-depth.html rather than using other tricks. Given that some or most of your codebase is using the element toggling approach and there is a new version of React with performance improvements chances are you will probably spend weeks into refactoring to benefit from it.

  2. Bugs - With JSX short circuit rendering you must remember not to use something like elements.length && elements.map(({ text }) => text) as given that the elements array has no members, JSX will print 0 instead of nothing. On the other side setting visibility with display: block almost certainly will lead to flex, inline, inline-block, table elements to be set to block. The second bug is harder to find as you need to deal with css styles or css-in-js.

  3. Consistency - Given that JSX short circuit rendering is the recommended method by the maintainers of React it will be present in most React projects. But say you mix it with the old school display toggling method and any new developers joining the team will question why you are using both. Mixing these will most probably lead to bugs as well where an element might be shown by JSX and in the same time hidden with display: none or vice versa.

  4. Debugging - using React Devtools or Elements while having lots of elements being set to display: none is a nightmare as it will be polluted with nodes that you simply don't need there

I reckon senior devs are used to toggle elements with display as it is considered old school. It might also be a legacy of converting your app from jQuery to React. It was the only way of making UIs back in the days. Some habits or shall I say mental models are quite sticky. Now days in a React project I will consider the above a hack.

I would advice against using any other way of toggling visibility of markup in React but the standard JSX short circuit rendering isShown && <div />. In my long experience of writing React apps I try to stick to the simplest and most expressive code, that all developers from uni graduates, to juniors, to seniors would expect as per best practices and wouldn't have trouble reading, so they reuse rather than write the nth version of the same component.

EDIT: As it was mentioned in other answers, transition animations are usually done with react-transition-group package that is only working with JSX short circuit rendering.

how to hide and show a div in react

Typical way

The most common pattern to this is selectively rendering the element based on state.

class Foo extends React.Component {

state = { showing: true };

render() {
const { showing } = this.state;
return (
<div>
<button onClick={() => this.setState({ showing: !showing })}>toggle</button>
{ showing
? <div>This is visible</div>
: null
}
</div>
)
}
}

Alternative

You can also use a style based on state. This is less common, but can be useful when you have complex components inside that div - one recent example, I had a complex non-React D3 graph within a toggle-able component, initially, I used the first method above, but caused quite a bit of lagging when flicking the div on/off because D3 was cycling up again.

Generally use the first approach though, unless you have a reason to use the alternative.

class Foo extends React.Component {

state = { showing: true };

render() {
const { showing } = this.state;
return (
<div>
<button onClick={() => this.setState({ showing: !showing })}>toggle</button>
<div style={{ display: (showing ? 'block' : 'none') }}>This is visible</div>
</div>
)
}
}

Note

I use the ?: ternary operator instead of && - I'm a strong believer that the use of && is relying on a side effect of that operator to achieve a certain outcome. It works, don't get me wrong, but the ternary operator, in my opinion, is far more expressive and was designed to be a conditional.

This last bit is just my opinion - so I'm not questioning the use of &&.

Show and hide different div in reactjs

You can do something like that:

import { useState } from "react";

export default function HealthcareProvider() {
const [hide, setHide] = useState(false);

const toggleHide = () => {
setHide(!hide);
};

return (
<div>
<div className="firstdiv"
style={{ display: hide ? "block" : "none" }}>
First Div Content
</div>
<div className="Seconddiv" style={{ display: hide ? "none" : "block" }}>
Second Div Content
</div>
<button onClick={toggleHide}>First Button</button>
<button onClick={toggleHide}>Second Button</button>
</div>
);
}

React js - Show or hide a div

The issue is that the button is inside a <form>. So any click on that button will submit the form and refresh the page.

Can I make a <button> not submit a form?

You need to add a type="button" to your <button>

import React, { useState } from "react";

function Hide() {
return (
<div>
<Mycomp />
</div>
);
}

function Mycomp() {
const [dp, setDp] = useState(false);

return (
<form>
<button
type="button"
onClick={() => setDp(!dp)}
>
Test
</button>
{dp && <div>Test</div>}
</form>
);
}

export default Hide;

Hide/Show components in react native

I would do something like this:

var myComponent = React.createComponent({

getInitialState: function () {
return {
showCancel: false,
};
},

toggleCancel: function () {
this.setState({
showCancel: !this.state.showCancel
});
}

_renderCancel: function () {
if (this.state.showCancel) {
return (
<TouchableHighlight
onPress={this.toggleCancel()}>
<View>
<Text style={styles.cancelButtonText}>Cancel</Text>
</View>
</TouchableHighlight>
);
} else {
return null;
}
},

render: function () {
return (
<TextInput
onFocus={this.toggleCancel()}
onChangeText={(text) => this.doSearch({input: text})} />
{this._renderCancel()}
);
}

});

React - hide content with button

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;


Related Topics



Leave a reply



Submit