How to avoid use of document.getElementById in Reactjs? [duplicate] - javascript

How do I select certain bars in react.js?
This is my code:
var Progressbar = React.createClass({
getInitialState: function () {
return { completed: this.props.completed };
},
addPrecent: function (value) {
this.props.completed += value;
this.setState({ completed: this.props.completed });
},
render: function () {
var completed = this.props.completed;
if (completed < 0) { completed = 0 };
return (...);
}
I want to use this React component:
var App = React.createClass({
getInitialState: function () {
return { baction: 'Progress1' };
},
handleChange: function (e) {
var value = e.target.value;
console.log(value);
this.setState({ baction: value });
},
handleClick10: function (e) {
console.log('You clicked: ', this.state.baction);
document.getElementById(this.state.baction).addPrecent(10);
},
render: function () {
return (
<div class="center">Progress Bars Demo
<Progressbar completed={25} id="Progress1" />
<h2 class="center"></h2>
<Progressbar completed={50} id="Progress2" />
<h2 class="center"></h2>
<Progressbar completed={75} id="Progress3" />
<h2 class="center"></h2>
<span>
<select name='selectbar' id='selectbar' value={this.state.baction} onChange={this.handleChange}>
<option value="Progress1">#Progress1</option>
<option value="Progress2">#Progress2</option>
<option value="Progress3">#Progress3</option>
</select>
<input type="button" onClick={this.handleClick10} value="+10" />
<button>+25</button>
<button>-10</button>
<button>-25</button>
</span>
</div>
)
}
});
I want to execute the handleClick10 function and perform the operation for my selected progressbar.
But the result I get is:
You clicked: Progress1
TypeError: document.getElementById(...) is null
How do I select the certain Element in react.js?

You can do that by specifying the ref
EDIT: In react v16.8.0 with function component, you can define a ref with useRef. Note that when you specify a ref on a function component, you need to use React.forwardRef on it to forward the ref to the DOM element of use useImperativeHandle to to expose certain functions from within the function component
Ex:
const Child1 = React.forwardRef((props, ref) => {
return <div ref={ref}>Child1</div>
});
const Child2 = React.forwardRef((props, ref) => {
const handleClick= () =>{};
useImperativeHandle(ref,() => ({
handleClick
}))
return <div>Child2</div>
});
const App = () => {
const child1 = useRef(null);
const child2 = useRef(null);
return (
<>
<Child1 ref={child1} />
<Child1 ref={child1} />
</>
)
}
EDIT:
In React 16.3+, use React.createRef() to create your ref:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
In order to access the element, use:
const node = this.myRef.current;
DOC for using React.createRef()
EDIT
However facebook advises against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases.
From the docs:
Legacy API: String Refs
If you worked with React before, you might be
familiar with an older API where the ref attribute is a string, like
"textInput", and the DOM node is accessed as this.refs.textInput. We
advise against it because string refs have some issues, are considered
legacy, and are likely to be removed in one of the future releases. If
you're currently using this.refs.textInput to access refs, we
recommend the callback pattern instead.
A recommended way for React 16.2 and earlier is to use the callback pattern:
<Progressbar completed={25} id="Progress1" ref={(input) => {this.Progress[0] = input }}/>
<h2 class="center"></h2>
<Progressbar completed={50} id="Progress2" ref={(input) => {this.Progress[1] = input }}/>
<h2 class="center"></h2>
<Progressbar completed={75} id="Progress3" ref={(input) => {this.Progress[2] = input }}/>
DOC for using callback
Even older versions of react defined refs using string like below
<Progressbar completed={25} id="Progress1" ref="Progress1"/>
<h2 class="center"></h2>
<Progressbar completed={50} id="Progress2" ref="Progress2"/>
<h2 class="center"></h2>
<Progressbar completed={75} id="Progress3" ref="Progress3"/>
In order to get the element just do
var object = this.refs.Progress1;
Remember to use this inside an arrow function block like:
print = () => {
var object = this.refs.Progress1;
}
and so on...

For getting the element in react you need to use ref and inside the function you can use the ReactDOM.findDOMNode method.
But what I like to do more is to call the ref right inside the event
<input type="text" ref={ref => this.myTextInput = ref} />
This is some good link to help you figure out.

With newer versions of React you can use and manipulate the DOM via hooks like this:
import React, { useEffect, useRef } from "react";
const MyComponent = () => {
const myContainer = useRef(null);
useEffect(() => {
console.log("myContainer..", myContainer.current);
});
return (
<>
<h1>Ref with react</h1>
<div ref={myContainer}>I can use the DOM with react ref</div>
</>
);
};
export default MyComponent;
Whenever you want to access your DOM element just use myContainer.current

You can replace
document.getElementById(this.state.baction).addPrecent(10);
with
this.refs[this.state.baction].addPrecent(10);
<Progressbar completed={25} ref="Progress1" id="Progress1"/>

Disclaimer: While the top answer is probably a better solution, as a beginner it's a lot to take in when all you want is something very simple. This is intended as a more direct answer to your original question "How can I select certain elements in React"
I think the confusion in your question is because you have React components which you are being passed the id "Progress1", "Progress2" etc. I believe this is not setting the html attribute 'id', but the React component property. e.g.
class ProgressBar extends React.Component {
constructor(props) {
super(props)
this.state = {
id: this.props.id <--- ID set from <ProgressBar id="Progress1"/>
}
}
}
As mentioned in some of the answers above you absolutely can use document.querySelector inside of your React app, but you have to be clear that it is selecting the html output of your components' render methods. So assuming your render output looks like this:
render () {
const id = this.state.id
return (<div id={"progress-bar-" + id}></div>)
}
Then you can elsewhere do a normal javascript querySelector call like this:
let element = document.querySelector('#progress-bar-Progress1')

You have to follow two different ways to do it in Class and Functional components.
For class components
<input type="text" ref={ref => this.myTextInput = ref} />
Look at the above code. Use "ref" attribute to refer to the relevant element. Then you will be able to refer to that element using that reference. In this example, I can use "this.myTextInput" to refer to the above input element.
For functional components
const textInput = useRef(null)
Use the "useRef" hook and set that variable name as the value of the "ref" attribute of the element you want to refer to (like below).
<input type="text" ref={textInput} />
An example for this on functional components.
import React, {useRef} from 'react'
function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it
const textInput = useRef(null);
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input type="text" ref={textInput} />
</div>
);
}
Want to learn more? Here you go

Since React uses JSX code to create an HTML we cannot refer dom using regulation methods like documment.querySelector or getElementById.
Instead we can use React ref system to access and manipulate Dom as shown in below example:
constructor(props){
super(props);
this.imageRef = React.createRef(); // create react ref
}
componentDidMount(){
**console.log(this.imageRef)** // acessing the attributes of img tag when dom loads
}
render = (props) => {
const {urls,description} = this.props.image;
return (
<img
**ref = {this.imageRef} // assign the ref of img tag here**
src = {urls.regular}
alt = {description}
/>
);
}
}

In my case, I wasn't able to use ref because elements were somewhere between many child components and I have to access them by class and id instead of ref. So, trying with useEffect hook didn't work as it can't find the element:
useEffect(() => {
const el1 = document.querySelector('.el1')
const el2 = document.querySelector('.el2')
}, [])
The element is undefined because when it is mounted the children components also doesn't mounted before this parent component.
So, what I did is to use timeout:
useEffect(() => {
const timer = setTimeout(() => {
const el1 = document.querySelector('.el1')
const el2 = document.querySelector('.el2')
},500)
return () => {
clearTimeout(timer)
}
}, [])
Now, it worked fine. It found the DOM and I was able to manipulate with them. Hope, this helps someone!

The equivalent of document.getElementById() in React is document.querySelector().

Related

How to set a ref when using React.cloneElement on a Function component?

I'm writing a Tooltip component and came across the following problem -
Function components cannot be given refs
My code looks like this
Component that includes the Tooltip:
<Tooltip title="Title" description="Description">
<Selection value={copy.value} label={copy.label} />
</Tooltip>
Tooltip component:
import React, { useRef } from 'react'
const Tooltip = props => {
const myRef = useRef()
const child = React.cloneElement(props.children, {
onMouseEnter: () => { /* placeholder */ },
onMouseLeave: () => { /* placeholder */ },
ref: myRef,
})
const TooltipOverlay = () => {
// will be a div wrapped in react Portal
return null
}
return (
<>
{child}
<TooltipOverlay />
</>
)
}
export default Tooltip
My goal is to not have a visible wrapper in the DOM like div/span or similar.
I need the ref to be able to relatively position TooltipOverlay in the Tooltip component.
All solutions are welcome as long as long as goals above are fulfilled.
I saw this done in rsuite library, not sure how.
Had the same issue and couldn't find a way to do what you wanted.
As a workaround and I guess the usual way is to let the user of the Tooltip pass the ref down and then you can intercept it with forwardRef.
const Tooltip = forwardRef((props, myRef) => {
// now you can clone without a ref and have access to the ref.
})
The user of the tooltip needs to pass a ref however:
const childRef = useRef()
<Tooltip ref={childRef}>
<div ref={childRef} />
</Tooltip>

Can't pass useState() 'set' function to grand child

I'm having issues trying to get my useState variable to work. I create the state in my grandparent then pass it into my parent. Here's a simplified version of my code:
export function Grandparent(){
return(
<div>
const [selectedID, setSelectedID] = useState("0")
<Parent setSelectedID2={setSelectedID} .../> //(elipses just mean that I'm passing other params too)
<div />
)}
Parent:
const Parent = ({setSelectedID2 ...}) => {
return(
<div>
{setSelectedID2("5")} //works
<Child setSelectedID3={setSelectedID2} />
</div>
)
}
From the parent I can use 'setSelectedID2' like a function and can change the state. However, when I try to use it in the child component below I get an error stating 'setSelectedID3' is not a function. I'm pretty new to react so I'm not sure if I'm completely missing something. Why can I use the 'set' function in parent but not child when they're getting passed the same way?
Child:
const Child = ({setSelectedID3 ...}) => {
return(
<div >
{setSelectedID3("10")} //results in error
</div>
);
};
In React you make your calculations within the components/functions (it's the js part) and then what you return from them is JSX (it's the html part).
export function Grandparent(){
const [selectedID, setSelectedID] = useState("0");
return(
<div>
<Parent setSelectedID2={setSelectedID} .../> //(elipses just mean that I'm passing other params too)
<div />
)}
You can also use (but not define!) some js variables in JSX, as long as they are "renderable" by JSX (they are not Objects - look for React console warnings).
That's your React.101 :)
Here's a working example with everything you have listed here. Props are passed and the function is called in each.
You don't need to name your props 1,2,3.., they are scoped to the function so it's fine if they are the same.
I moved useState and function calls above the return statement, because that's where that logic should go in a component. The jsx is only used for logic dealing with your display/output.
https://codesandbox.io/s/stupefied-tree-uiqw5?file=/src/App.js
Also, I created a working example with a onClick since that's what you will be doing.
https://codesandbox.io/s/compassionate-violet-dt897?file=/src/App.js
import React, { useState } from "react";
export default function App() {
return <Grandparent />;
}
const Grandparent = () => {
const [selectedID, setSelectedID] = useState("0");
return (
<div>
{selectedID}
<Parent setSelectedID={setSelectedID} selectedID={selectedID} />
</div>
);
};
const Parent = ({ selectedID, setSelectedID }) => {
setSelectedID("5");
return (
<div>
{selectedID}
<Child setSelectedID={setSelectedID} selectedID={selectedID} />
</div>
);
};
const Child = ({ selectedID, setSelectedID }) => {
setSelectedID("10");
return <div>{selectedID}</div>;
};
output
10
10
10
const [selectedID, setSelectedID] = useState("0")
should be outside return

export Hooks in React for Nested Components?

I'm exporting hooks with nested components so that the parent can toggle state of a child. How can I make this toggle work with hooks instead of classic classes or old school functions?
Child Component
export let visible;
export let setVisible = () => {};
export const ToggleSwitch = () => {
const [visible, setVisibile] = useState(false);
return visible && (
<MyComponent />
)
}
Parent
import * as ToggleSwitch from "ToggleSwitch";
export const Parent: React.FC<props> = (props) => {
return (
<div>
<button onClick={() => ToggleSwitch.setVisible(true)} />
</div>
)
}
Error: Linter says [setVisible] is unused variable in the child... (but required in the parent)
You can move visible state to parent like this:
const Child = ({ visible }) => {
return visible && <h2>Child</h2>;
};
const Parent = () => {
const [visible, setVisible] = React.useState(false);
return (
<div>
<h1>Parent</h1>
<Child visible={visible} />
<button onClick={() => setVisible(visible => !visible)}>
Toggle
</button>
</div>
);
};
If you have many child-components you should make more complex logic in setVisible. Put object to useState where properties of that object will be all names(Ids) of child-components
as you know React is one-way data binding so if you wanna pass any props or state you have only one way to do that by passing it from parent to child component and if the logic becomes bigger you have to make it as a global state by using state management library or context API with react hooks use reducer and use effect.

ReactJS: How to test for a ref?

This is a function used in a react component. As you can see I'm using ref to get the focus on a specific input element of another component.
myFunction (param) {
this.refInput && this.refInput.focus()
}
Now I would like to test via jestJS for the focus() to have been called.
it('myFunction() should call focus()', () => {
// SETUP
const refInput = { focus: jest.fn() }
wrapper = shallow(<Example
refInput={refInput}
/>)
// EXECUTE
wrapper.instance().myFunction('anything')
// VERIFY
expect(refInput.focus).toHaveBeenCalled()
})
But this is wrong, as I pass the refInput as a property. But it is not this.props.refInput, so this attempt is not working.
How do I setup a ref in my test?
Update
This is how my component looks like:
class Example extends Component {
setStep (state) {
state.term = ''
this.setState(state)
this.refInput && this.refInput.focus()
}
render () {
return (
<div>
<Step onClick={this.setStep.bind(this, this.state)}>
<Step.Content title='title' description='description' />
</Step>
<Input ref={input => { this.refInput = input }} />
</div>
)
}
}
Try doing something like this:
it('myFunction() should call focus()', () => {
// SETUP
wrapper = mount(<Example />)
// EXECUTE
wrapper.instance().myFunction('anything')
// VERIFY
const elem = wrapper.find('#foo');
const focusedElement = document.activeElement;
expect(elem.matchesElement(focusedElement)).to.equal(true);
})
Points to note:
Use Mount rather than Shallow, as #Marouen Mhiri commented, shallow rendering can't hold a ref
You don't need to pass ref as props (in fact it's wrong)
Where I have wrapper.find('#foo'), replace foo by class/id of the DOM element in Input

Show or hide element in React

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>
```

Categories