Jessie Richardson
Jessie Richardson

Reputation: 958

Calling an External Function in a React Component

I have a need, in a site I'm building, for a list component that is reused several times. However, the list is purely for rendering and is not responsible for the state of the app at all. I know you either cannot, or are not supposed to have dumb components containing any logic, but I am not sure how to proceed without using a smart component, which is entirely unnecessary. Here is my smart component that works:

class Menu extends Component {
    renderItems(items) {
        return this.props.items.map((i, index) => {
             return (
                 <li key={index} style={{marginLeft: 10}}>
                    {i}
                </li>
            )
        });
    }
    render() {
        const { listStyle } = styles;
        return (
            <div>
                <ul style={listStyle}>
                    {this.renderItems()}
                </ul>
            </div>
        )
    }
}

And I've tried this:

function Menu(props) {
    return props.items.map((i, index) => {
             <li key={index} style={{marginLeft: 10}}>
                {i}
            </li>
    });
}

And then calling it inside Nav like this, which does not throw an error but does not render anything from menu either:

const Nav = () => {
    const { listStyle, containerStyle } = styles;
    return (
        <div style={containerStyle}>
            <Logo url={'#'}
                    src={PickAPlayLogo}
                    width={300} />
            <Menu items={pageLinks} />
            <Menu items={socialMediaLinks} />
            <Logo url={'#'}
                    src={AppStoreLogo}
                    width={170} />
        </div>
    );
};

Also, worth noting, I have never come across a function that is supposed to be rendered like a component, but was trying it based on the example on this page

Upvotes: 1

Views: 1615

Answers (2)

Paul Asetre
Paul Asetre

Reputation: 81

Heres an answer similar to what you have going on

function Menu(props) {
    this.renderItems = () => {
        return (
            <ul>
                {props.items.map((i, index) => {
                   return (
                       <li>{i}</li>
                   )
                })}
            </ul
        )
    }

    return(
        this.renderItems()
    )
}

Upvotes: 1

Jessie Richardson
Jessie Richardson

Reputation: 958

Here we go:

function Menu(props) {
    const {listStyle} = styles;
    const listItems = props.items.map((i, index) =>
                <li key={index} style={{marginLeft: 10}}>
                    {i}
                </li>
        );
    return (
        <ul style={listStyle}>{listItems}</ul>
    );
}

Upvotes: 0

Related Questions