Reputation: 93
I am trying to create an object with margin values as props. Then I set the style of my div to that same object, adopting the margins then.
import React from 'react'
import Link from 'gatsby-link'
import { styles } from '../styles.js'
const margins = {
marginTop: this.props.top,
marginBottom: this.props.bot
}
const Header = ({ siteTitle }, props) => (
<div style={margins}>
<h1> Content </h1>
</div>
)
export default Header
Yet it is not working. How can I get the props to work?
Thank you
Upvotes: 0
Views: 219
Reputation: 36895
margins
is a simple object.
There might be mulitple walkarounds but I'd recommend you to check out styled-components
(refer to Adapting based on props) for such scenario.
import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
const Content = styled.div`
margin-top: ${props => props.top};
margin-bottom: ${props => props.bot};
`;
const Header = ({ siteTitle }, props) => (
// <div style={margins}>
// <h1> Content </h1>
// </div>
<Content top={"100px"} bottom={"500px"}>
Some Content!
</Content>
);
function App() {
return (
<div className="App">
<Header />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You can find some of the examples where I used styled-components
for a gatsby site.
https://github.com/dance2die/landingpage/blob/master/src/components/Emojis.js#L8
Declared an Emoji component and,
const Emoji = styled.img.attrs({
src: props => props.src,
alt: props => props.alt,
})`
height: 3rem;
margin-right: 2rem;
`
Used like so by passing src
& alt
description.
const CreationsEmoji = () => (
<Emoji src={creationsEmoji} alt="Creations Emoji" />
)
Upvotes: 1