Search code examples
reactjsreact-component

Make Font Awesome component reusable in React


Is there a way I can make my component reusable?

I am using react-native-fontawesome npm

here is the original component:

export default class Awesome extends Component {
    render() {
        return (
            <View>
                <TouchableHighlight>
                    <Text
                        style={{ margin: 10, fontSize: 15, textAlign: 'left' }}
                    >
                        <FontAwesome>{Icons.chevronLeft}</FontAwesome>//I want to change this line
                        Text
                    </Text>
                </TouchableHighlight>
            </View>
        );
    } }

I want to pass in my parent component something like:

 <Awesome icon="chevronLeft" />

and then in my Awesome use

 <FontAwesome>{Icons.this.props.icon}</FontAwesome>

Obviously this is not the way to do it, but I do not have any good ideas.


Solution

  • Found the way, I can use switch statement

    <Awesome icon="Back" />
    <Awesome icon="Heart" />
    <Awesome icon="Share" />
    <Awesome icon="More" />
    

    and in my Child component:

    export default class Awesome extends Component { render() {

        switch (this.props.icon) {
            case 'Back':
                return <FontAwesome>{Icons.chevronLeft}</FontAwesome>;
            case 'Heart':
                return <FontAwesome>{Icons.heart}</FontAwesome>;
            case 'Share':
                return <FontAwesome>{Icons.share}</FontAwesome>;
            case 'More':
                return <FontAwesome>{Icons.ellipsisH}</FontAwesome>;
    
            default:
                return <Text>HI</Text>;
        }
    }
    

    }