How to toggle a content of the single element in React JS?

Asked
Active3 hr before
Viewed126 times

9 Answers

elementtogglereactsinglecontent
90%

Instead of storing the boolean values of true/false in your component's toggled state, you can store the key from the data array instead.,Then, you can conditionally render the text below h1 based on the current toggled state,Find centralized, trusted content and collaborate around the technologies you use most.

Then, you can conditionally render the text below h1 based on the current toggled state

export default function App() {
  const [toggled, toggle] = useState("");
  return (
    <div className="App">
      {data.map(({ title, text, key }) => {
        return (
          <>
            <h1 onClick={() => toggle(key)}>{title} </h1>
            {toggled ===key ? (
              <>
                <p>{text}</p>
              </>
            ) : null}
          </>
        );
      })}
    </div>
  );
}
88%

Add the following to src/ToggleSwitch/ToggleSwitch.js:,In this directory, make two files: ToggleSwitch.js and ToggleSwitch.scss:,And this is what that looks like in SCSS. Add the following to src/ToggleSwitch/ToggleSwitch.scss:

Pretag
 Pretag team - issue, fix, solve, resolve
72%

Let's see this in action! We will only display the rest of the product name if it has something to display:,In modern React, a component is little more than a function whose job it is to return the value that is to be rendered. Just like regular functions, functional components can have multiple return values. If what the component renders is an "all or nothing" situation, the simplest way to control whether an element is rendered is to avoid returning any JSX at all, and return null instead.,We see that you have already chosen to receive marketing materials from us. If you wish to change this at any time you may do so by clicking here.

Because this if statement is not embedded inside of JSX but is just part of the regular JavaScript portion of the function, you are free to use any sort of JS construct that you like. In this example, if the product is not available, we're just going to return null.

const AddToCart = ({ available }) => {
  if (!available) return null;

  return (
    <div className="full tr">
      <button className="product--cart-button">Add to Cart</button>
    </div>
  );
};
load more v
65%

A component is a single unit, and combining multiple units creates a complete application. But what if we want to hide or show a component frequently?,Let’s say we have a component called Demo1, and we want to hide it based on the Boolean value true/false. We can use different conditional operators to achieve this functionality.,So based on the click event, the state values will be updated, and based on the Boolean value, the specific table row hides or shows into the DOM.

1import React, { Component } from "react";
2
3class Demo1 extends Component {
4  constructor() {
5    super();
6    this.state = {
7      name: "React"
8    };
9  }
10
11  render() {
12    return <div>This is Demo1 component</div>;
13  }
14}
15
16export default Demo1;
load more v
75%

If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context.,Using context, we can avoid passing props through intermediate elements:,Context provides a way to pass data through the component tree without having to pass props down manually at every level.

class App extends React.Component {
  render() {
    return <Toolbar theme="dark" />;
  }
}

function Toolbar(props) {
  // The Toolbar component must take an extra "theme" prop  // and pass it to the ThemedButton. This can become painful  // if every single button in the app needs to know the theme  // because it would have to be passed through all components.  return (
    <div>
      <ThemedButton theme={props.theme} />    </div>
  );
}

class ThemedButton extends React.Component {
  render() {
    return <Button theme={this.props.theme} />;
  }
}
load more v
40%

Switches toggle the state of a single setting on or off.,Switches are the preferred way to adjust settings on mobile. The option that the switch controls, as well as the state it’s in, should be made clear from the corresponding inline label.,Switch can be provided with a description thanks to the FormControlLabel component.

<FormGroup>
  <FormControlLabel
    control={<Switch size="small" checked={checked} onChange={toggleChecked} />}
    label="Small"
  />
  <FormControlLabel
    control={<Switch checked={checked} onChange={toggleChecked} />}
    label="Normal"
  />
</FormGroup>
load more v
22%

If the boolean value is true class name is added to the react element., If the boolean value is true class name is added to the react element. ,If the boolean value is false class name is removed from the react element.

import React, { useState } from "react";import "./styles.css";

export default function App() {
  const [isActive, setActive] = useState("false");
  const handleToggle = () => {
    setActive(!isActive);  };
  return (
    <div className={isActive ? "app" : null}>      <h1>Hello react</h1>
      <button onClick={handleToggle}>Toggle class</button>    </div>
  );
}
load more v
60%

When true, indicates that the view is an accessibility element. When a view is an accessibility element, it groups its children into a single selectable component. By default, all touchable elements are accessible.,A Boolean value indicating whether the accessibility elements contained within this accessibility element are hidden.,Use this property to assign a custom function to be called when someone activates an accessible element by double tapping on it while it's selected.

<View accessible={true}>  <Text>text one</Text>  <Text>text two</Text></View>
load more v
48%

Powered by Discourse, best viewed with JavaScript enabled,Hi Dereje1, thanks for taking your time. The code already contains everything you need. Have got a component CommentReply that hides and shows a form on toggle.,It’s funny, your codepen link actually works. clicking on a reply displays one form at a time and not all. I think it has to do with the arrow function ()=> …binding this to the context.

I want the reply form of the clicked element only to show. If it helps, below is my code.

import React, { Component } from 'react'

export default class CommentReply extends Component {
     constructor () {
        super()
        this.state = {
          isHidden: true
        }
    }

    toggleHidden () {
        this.setState({
          isHidden: !this.state.isHidden
        })
    }
	
    render() {
        const load = this.state.isHidden;
        return(
				<div className="actions">
                    <a className="reply" onClick={this.toggleHidden.bind(this)}>Reply</a>
                    <a className="save">Save</a>

                    {load ? <form className="ui reply form">
                        <div className="field">
                            <input type="hidden" name="StatusId" className="cp_coment"/>
                            <textarea className="cp_rep" name="content"></textarea>
                        </div>
                     </form>: ""}
                </div>
        );
    }
}
load more v

Other "element-toggle" queries related to "How to toggle a content of the single element in React JS?"