0

I'm doing a course of React Native, and in one class about "Custom Components" and "props" i came across this:

{...props.style}

when i asked the teacher told me this: Three dots in JavaScript is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed. Actually, here the style that comes through the props extends the current style.

but i'm very new with this and i didn't get it. could someone explain it to me with another/simpler words? maybe examples? i'll let the code here in case its needed:

THIS IS THE "CUSTOMBUTTON.JS":

import React from 'react';
import {
    Pressable,
    Text,
    StyleSheet,
} from 'react-native';

const MashButton = (props) => {
    return (
        <Pressable
            onPress={props.onPressFunction}
            hitSlop={{ top: 10, bottom: 10, right: 10, left: 10 }}
            android_ripple={{ color: '#00f' }}
            style={({ pressed }) => [
                { backgroundColor: pressed ? '#dddddd' : props.color },
                styles.button,
                {...props.style}
            ]}
        >
            <Text style={styles.text}>
                {props.title}
            </Text>
        </Pressable>
    )
}

const styles = StyleSheet.create({
    text: {
        color: '#000000',
        fontSize: 20,
        margin: 10,
        textAlign: 'center',
    },
    button: {
        width: 150,
        height: 50,
        alignItems: 'center',
    },
})

export default MashButton;

Then in the "APP.JS" there are these:

<MashButton
        onPressFunction={onPressHandler}
        title={submitted ? 'Clear' : 'Submit'}
        color={'#00ff00'}
      />
      <MashButton
        onPressFunction={() => { }}
        title={'Test'}
        color={'#ff00ff'}
        style={{ margin: 10 }}
      />
danistor_m
  • 79
  • 1
  • 10
  • 2
    Does this answer your question? [What do these three dots in React do?](https://stackoverflow.com/questions/31048953/what-do-these-three-dots-in-react-do) – evolutionxbox Jun 14 '21 at 16:03
  • 1
    See the linked threads for more details, but another way to word your teacher's answer: `{...props.style}` creates a shallow copy of props.style. (in this context, "shallow" means that it won't repeat the copying process on nested objects). So if `props.style` is an object like `{ margin: 5 }`, then it creates a new object that also looks like `{ margin: 5 }` – Nicholas Tower Jun 14 '21 at 16:12

0 Answers0