Invariant Violation: React.Children.only expected to receive a single React element child

Fabian Bosler picture Fabian Bosler · Jul 15, 2017 · Viewed 16.4k times · Source

I keep getting the invariant violation and I really don't know why ... it definitely has to do with the OverlayTriggers. When leaving them out everything works fine.

Imports:

import Col from 'react-bootstrap/lib/Col';
import Row from 'react-bootstrap/lib/Row';
import Tooltip from 'react-bootstrap/lib/Tooltip';
import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger';

supposed to render a list item with a Key/Value pair, where the Value has a tooltip:

const renderCustomField = (field,customFields) => {
    const tooltip = (<Tooltip id="tooltip">{customFields[field]['sub']}</Tooltip>)
    return (
        <li>
            <OverlayTrigger placement="top" overlay={tooltip}>
                {field}
            </OverlayTrigger>
        </li>
    )
}

The class that wants to render the customFields:

export default class EventHeaderCustomFields extends Component {
    render () {
        const customFieldsNames = Object.keys(this.props.customFields);

        return (
            <Col xs={12}>
                <h4><strong>Short overview:</strong></h4>
                <ul>
                {customFieldsNames.map(
                    (field) => renderCustomField(field,this.props.customFields)
                )}
                </ul>
            </Col>
        )
    }
}

EventHeaderCustomFields.propTypes = {
    eventData:PropTypes.object
};

Answer

Jibola picture Jibola · Jul 15, 2017

OverlayTrigger expects a React element child, wrapping {field} in span or any other valid React jsx element will fix this.

<li>
    <OverlayTrigger placement="top" overlay={tooltip}>
        <span>{field}</span>
    </OverlayTrigger>
</li>