Trinkflasche93
Trinkflasche93

Reputation: 89

React native - Set default values for component

I am trying to create a component (Button), which can be modified using some props. It should be possible to change the background color of the button. In case that this color is not set, a default value should be used. How can I achieve this? :)

import * as React from 'react';
import { StyleSheet } from 'react-native';
import { Button } from 'react-native-paper';

const button = (props) => {
    const [title, setTitle] = React.useState('');
    const [color, setColor] = React.useState('');
    const [icon, setIcon] = React.useState('');
    const [rounded, setRounded] = React.useState('');
    const [disabled, setDisabled] = React.useState('');

    React.useEffect(() => {
        setColor(props.color != null ? props.color : '#8a4a5s');
        setTitle(props.title);
        setIcon(props.icon);
        setRounded(props.rounded);
        setDisabled(props.disabled);
    }, [props.color, props.title, props.icon, props.rounded]);

    return (
        <Button icon={icon} mode="contained" color={color} onPress={() => console.log('Pressed')} disabled={disabled}>
            {title}
        </Button>
    );
};

export default button;

const styles = StyleSheet.create({
});

Thank you in advance!

Upvotes: 1

Views: 1436

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28414

You can set a default value by destructuring the props. Your component can be simplified to this given that the props are all for the Button component:

import React from 'react';
import { Button } from 'react-native-paper';

const CustomButton = ({ color = "#8a4a5s", title, ...props }) => (
  <Button
    {...props}
    color={color}
    mode="contained"
    onPress={() => console.log("Pressed")}
  >
    {title}
  </Button>
);

export default CustomButton;

Upvotes: 1

Related Questions