Roy
Roy

Reputation: 1922

Using props in React with styled components across components

I have a React component:

const StyledButton = styled.button`
    border: none;
    background: ${props => props.color};
    color: white;
    &:focus {
        outline: none;
    }
`;

const Button = (props) => {
    return (
        <StyledButton>{props.name}</StyledButton>
    )
};

and another component:

const NoteWindow = (props) => {
    return (
        <StyledNoteWindow className="NoteWindow">
            <StyledForm action="#" className="form">
                <StyledInput type="text" name="title" id="title" autoComplete="off" placeholder="Title" style={{fontSize: 60, fontWeight: 700}}/>
                <StyledInput type="text" name="content" id="content" autoComplete="off" placeholder="Content.." style={{fontSize: 20}}/>
            </StyledForm>
            <Button name="Discard" color="red"/>
            <Button name="Save" color="blue"/>
        </StyledNoteWindow>
    )
}

and I want the background of my button component to be the "color" attribute in the other element. How can I do that? (Everything is imported and exported)

Upvotes: 1

Views: 36

Answers (2)

wentjun
wentjun

Reputation: 42576

From what I can see, Button and StyledButton components accepts at least the following props, name and color.

Therefore, you will need to pass the props down to the StyledButton component:

const Button = ({ color, name }) => (
  <StyledButton color={color}>{name}</StyledButton>
);

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 203408

Destructure name to used as child/text of button, and spread the rest of the passed props to StyledButton.

const Button = ({ name, ...props }) => {
  return (
    <StyledButton {...props}>{name}</StyledButton>
  )
};

Upvotes: 0

Related Questions