It can be difficult to get text to wrap under a photo, especially if the photo and text are in a flex box that just gets wider for longer text and you don’t know in advance how wide the photo will be. You want the flex box to stay the width of the photo. However, there is an easy solution in react using a hook.
Here is an example to make the text wrap under the photo. The example assumes you have a photo from a third party source and you don’t know in advance how wide the photo is. Also, you are feeding the function props of name, photo, and description. The description needs to wrap under the photo..
Example code
import React, { useState } from 'react'; function Detail(props) { const [width, setWidth] = useState(0); const onImgLoad = ({ target: img }) => { // gets width of tour image setWidth(img.offsetWidth); } return ( <div> <div className="d-flex flex-column" > <div><h2>{props.name}</h2></div> <div > <img src={"https://example.com/" + props.photo} onLoad={onImgLoad} alt={props.name} /> </div> </div> <div style={{ width: width }}> <div > {props.description} </div> </div> </div> ); } export { Detail };
Using a react hook
This example makes use of a react useState hook to set the width property. The onLoad property of the img tag is used to trigger setting the width. Bootstrap classes were used to manage the flex boxes.