Render AMP components with React
npm install amp-react-componentsRender AMP components with React.
1. Support styled-components by passed-in className prop.
2. Attaches className prop to class prop of AMP elements for supporting HTML class attribute. Now React does't support custom element attributes, so the will be rendered as
3. Render script tag with type=application/json to support AMP components, such as amp-animation and amp-bind
npm i amp-react-components
`Usage
- Common jS
`js
// import from package entry point
const amp = require('amp-react-components')
`
`js
// only import specific component
const AmpLightbox = require('amp-react-components/lib/components/AmpLightbox')
`- ESM
`js
// import from package entry point
import { AmpImg, AmpLightbox } from 'amp-react-components'
`
`js
// only import specific component
import AspectRatioImg from 'amp-react-components/es/components/AmpLightbox'
`
Example
- CSS Module
`css
// style.css
.img {
position: relative;
border-radius: 8px;
border: solid 1px #e0e4e9;
box-sizing: border-box; > img {
border-radius: 8px;
}
}
``js
// index.js
import { AmpImg } from 'amp-react-components'
import styles from './style.css'function Compoment({...}) {
return (
className ={styles.img}
src={image}
width="1"
height="1"
layout="responsive"
/>
)
}
`- Styled Components
`js
import styled from 'styled-components'
import { AmpImg } from 'amp-react-components'const StyledAmpImg = styled(AmpImg)
> img {
border-radius: 8px;
}`
function Compoment({...}) {
return (
width="1"
height="1"
layout="responsive"
/>
)
}
- AMP Component (AmpState) with Script Tag`js
import { AmpImg, AmpState } from 'amp-react-components'
function Compoment({...}) {
const id = "myAnimals"
const state = {
"dog": {
"imageUrl": "/img/dog.jpg",
"style": "greenBackground"
},
"cat": {
"imageUrl": "/img/cat.jpg",
"style": "redBackground"
}
}
return (
<>
This is a dog.
Each animal has a different background color.
- AMP.setState
`js
import { ampSetState } from 'amp-react-components/utils'function Button(){
const state = {
foo: 'bar'
}
return (
on=
tap:${ampSetState(state)}
>
click me
)
}
``