React example of forcing text to wrap under a photo

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       
    return (
            <div className="d-flex flex-column" >
                <div >
                    <img  src={"" +}
                        alt={} />
            <div style={{ width: width }}>
                <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.

Leave a Reply

Your email address will not be published. Required fields are marked *