Matthias Güntert
Matthias Güntert

Reputation: 4668

How can I render <Card.Text> as <div> element and not as <p>?

For <Card.Body> there seems to be a parameter named as which is of type elementType and defaults to <div>.

https://react-bootstrap.github.io/components/cards/#card-body-props

Now <Card.Text> defaults to <p> which results in warnings on my website as I have nested <div> elements inside <Card.Text>

Warning: validateDOMNesting(...): cannot appear as a descendant of <p>

So basically two questions:

  1. How can I change/set the elementtype on Card.Body? The following attempts did not get reflected in the produced html (checked with Chrome DevTools): <Card.Body as="p">...</Card.Body> nor did this <Card.Body as="<p>">...</Card.Body>

  2. How can I change the elementtype on <Card.Text>?


This is what my component looks like

import React from "react"
import { Link } from "gatsby"
import Img from "gatsby-image"
import Card from "react-bootstrap/Card"
import Tags from "./tags"
import TimeToRead from "./time-to-read"

const Post = ({ title, slug, date, body, fluid, tags, timeToRead }) => {
  return (
    <Card className="mb-3 shadow-lg" bg="concrete" id="hoverable">
      <Link to={slug}>
        <Img
          className="card-image-top"
          style={{ maxHeight: "150px" }}
          fluid={fluid}
        ></Img>
        <Card.ImgOverlay
          style={{
            pointerEvents: "none",
          }}
        >
          <Tags tags={tags} />
        </Card.ImgOverlay>
      </Link>

      <Card.Body>
        <Card.Title>{title}</Card.Title>
        <Card.Subtitle>
          <div className="d-flex justify-content-between">
            <span className="text-info">{date}</span>
            <TimeToRead minutes={timeToRead} />
          </div>
        </Card.Subtitle>
        <hr />
        <Card.Text as="div">{body}</Card.Text>
        <Link
          to={slug}
          className="btn btn-outline-primary float-right text-uppercase"
        >
          Read more
        </Link>
      </Card.Body>
    </Card>
  )
}

export default Post

Upvotes: 5

Views: 1641

Answers (1)

cadebe
cadebe

Reputation: 691

I had the same problem, essentially. I used an unordered list inside the text for the <Card.Body> and the console displayed the following warning:

validateDOMNesting(...): <ul> cannot appear as descendent of <p>.

Wrapping the list content inside a <div> just added to the warning list. As suggested above, I amended the <Card.Text> tag, but as follows:

 <Card.Text as="div">

The warning disappeared and the text renders. Note, you have to adjust the styling, depending on how the styling cascade is configured.

Upvotes: 6

Related Questions