niina
niina

Reputation: 119

How to refactor code for switch case using react?

I have a side panel and have some list items in it.I am using switch case to return list item. Instead of repeating code for list item i have created a listitem component and pass icon and timestamp to it also render children in the listitem component.

Below is the code,

switch(item.type) {
    case 'uploaded':
        return (
            <ListItem icon={<Svg/>} text={name + 
            'created item' + item.name} timestamp={timestamp}>
                <div className="image">
                    <Image
                        width={70}
                        height={70}
                        item_id={item.id}
                    />
                </div>
            </ListItem>
        );
    case 'deleted':
        return (
            <ListItem icon={<Svg/>} text={name + 
               'deleted item' + item.name} timestamp={timestamp}>
            </ListItem>
        );


function ListItem(props) {
    return (
        <li className="item">
            <div className="details">
                {props.icon}
                <span>{props.text}</span>
            </div>
            {props.children}
            <Timestamp>{props.timestamp}</Timestamp>
        </li>
    );
} 

The above code works..

But i want a more neat way to do this. instead of passing text as a prop to ListItem is there way a i can include it in props.children and use it in the Listitem..it would be added after div with details classname...i want it to be with in details div and image after div with classname details..

How can i do it. Thanks.

Upvotes: 0

Views: 109

Answers (1)

claud.io
claud.io

Reputation: 1963

You could move everything inside a new component passing your type:

function InnerItem(props) {
     switch(props.type) {
        case 'uploaded':
            return (
                <ListItem icon={<Svg/>} text={name + 
                'created item' + item.name} timestamp={timestamp}>
                    <div className="image">
                        <Image
                            width={70}
                            height={70}
                            item_id={item.id}
                        />
                    </div>
                </ListItem>
            );
        case 'deleted':
            return (
                <ListItem icon={<Svg/>} text={name + 
                   'deleted item' + item.name} timestamp={timestamp}>
                </ListItem>
            );
 }

    function ListItem(props) {
        return (
            <li className="item">
                <div className="details">
                    {props.icon}
                    <span>{props.text}</span>
                </div>
                 <InnerItem {...item}/>
                <Timestamp>{props.timestamp}</Timestamp>
            </li>
        );
    } 

Upvotes: 0

Related Questions