I'm making a website using React.
When my website has lots of text, I'll show a button such as show more or less.
In my project, It works well, but always show a warning about validateDOMNesting(...): <button>
My sample code like this.
const [show, setShow] = useState(false);
function handleShow() {
  show ? setShow(false) : setShow(true);
}
<CardActionArea>
  <Button onClick={handleShow}> 
    { show ? text : text.substr(0, 100) + "..." }
  </Button>
</CardActionArea>
I think CardActionArea is a button component, it makes a nested button now.
But if I declare href property in button, it doesn't make a warning.
Is there a good way that doesn't make a warning not using href property?
Issue: With your code you've placed a button within a button which is a no-no.
From the Material-UI CardActionArea docs
Inheritance
The props of the
ButtonBasecomponent are also available. You can take advantage of this behavior to target nested components.
And if you cruise on over to the ButtonBase docs you'll see it is by default a 'button' component.

Option 1: Move button logic to CardActionArea and set the component prop of the Button to anything not a button, like a span. This makes the entire card action area have the onClick handler and responsive.
<CardActionArea onClick={handleShow}>
  <Button component="span"> 
    { show ? text : text.substr(0, 100) + "..." }
  </Button>
</CardActionArea>
Option 2: Keep as-is and set the component prop of the CardActionArea to anything other than 'button'. This will leave only the button with the onClick handler, the card action area will register clicks, i.e. the ripple effect, but will by unresponsive otherwise.
<CardActionArea component="span">
  <Button onClick={handleShow}> 
    { show ? text : text.substr(0, 100) + "..." }
  </Button>
</CardActionArea>
Between the two option 1 is, IMO, the preferred option as it makes the entire action area responsive, but this is based entirely on only the facts presented and your needs/design could be different or more complex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With