Tomáš Nosek
Tomáš Nosek

Reputation: 333

How to only select element from current component in React

I am completely new to react. I created a component like this:

    import React from "react"

function Product(props) {
    return (
        <div>
            <h2>{props.product.name}</h2>
            <button onClick={() => document.querySelector(".desc").style.display="block"}>More info</button>
            <p className="desc" style={{display: "none"}}>{props.product.price.toLocaleString("en-US", { style: "currency", currency: "USD" })} - {props.product.description}</p>
        </div>
    )
}

export default Product

Then I render a few of the components in the App. The purpose of the button is that it should show the information about the specific component. However this way, Im always selecting the first element with "desc" class name.

How to select the element from the current component easily?

Upvotes: 0

Views: 1181

Answers (2)

trixn
trixn

Reputation: 16309

How to select the element from the current component easily?

You wouldn't do it like that with react. The way to alter what your app shows is to alter the state. Create a component that has state that reflects what should be rendered. Then when an interaction happens (e.g. a button click) alter the state. React will re-render and show your app according to the new state:

function Product(props) {
  // create a state that holds the information if details should be displayed
  // we initially set it to false
  const [showDetails, setShowDetails] = useState(false);

  // create a callback that toggles the state
  // we will pass that to the onClick handler of our button
  const handleToggleInfo = () => setShowDetails(current => !current);

  return (
    <div>
      <h2>{props.product.name}</h2>
      <button onClick={handleToggleInfo}>More info</button>

      {showDetails && (
        /* this will only get rendered if showDetails is true */
        /* you don't need any css to "hide" it, it will just not render in the first place */
        <p className="desc">
          {`${props.product.price.toLocaleString("en-US", {
            style: "currency",
            currency: "USD"
          })} - ${props.product.description}`}
        </p>
      )}
    </div>
  );
}

Edit old-grass-fichq

Generally speaking it isn't necessary with react to select DOM elements and alter them. This is all handled by state updates and re-rendering the components. A component describes the DOM given a current state and props. If you want your DOM to change describe that with state and props.

If you are not familiar with state in react you should really search for a good tutorial that covers that. It is a basic core concept of react. Without it you will not be able to create an app that has interactivity.

Tip: If you want to display a string that is constructed from multiple parts use template strings.

Upvotes: 1

ludwiguer
ludwiguer

Reputation: 2245

This is not reactish, you need to leverage your UI changes to the state

function Product(props) {
    const [isDescVisible, setIsDescVisible] = useState(false);
    return (
        <div>
            <h2>{props.product.name}</h2>
            <button onClick={() => setIsDescVisible(true)}>More info</button>
            {isDescVisible &&
              <p className="desc">
                {props.product.price.toLocaleString("en-US", { style: "currency", currency: "USD" })} - {props.product.description}
              </p>
            }
        </div>
    )
}

Upvotes: 1

Related Questions