2

In this answer it's explained how to use the undocumented is feature to add a custom attribute to a React element. However, I'd like to add an attribute for use with amp-bind which is surrounded by brackets. When I try this the attribute is not added:

const ampProps = {
  '[class]': 'foo.bar',
};

return <div is {...ampProps}><MyComponent></div>

How can I add the custom attribute?

Community
  • 1
  • 1
Gil Birman
  • 35,242
  • 14
  • 75
  • 119
  • const ampProps = class => ({ [class]: 'foo.bar', }); return
    – elmeister Apr 08 '17 at 16:21
  • the point is to have the brackets in the prop. your proposed solution doesn't do that – Gil Birman Apr 08 '17 at 18:11
  • Does this help? https://github.com/zeit/next.js/blob/master/examples/with-amp/pages/_document.js – Irvin Lim Apr 08 '17 at 19:20
  • There are only two options - or you will have brackets like in your sample - inside of a string - or you will not have brackets, since [something] will be converted to something value. – elmeister Apr 08 '17 at 23:54
  • For AMP bind with react you can use its alternate syntax mentioned in official doc of amp-bind. https://amp.dev/documentation/components/amp-bind/#bindings – Rahul Jain Nov 21 '19 at 07:47

3 Answers3

3

For AMP bind with react you can use its alternate syntax mentioned in official doc of amp-bind.

An alternative, XML-compatible syntax can also be used in the form of data-amp-bind-property

Example You can write [text] binding as data-amp-bind-text which will not give error in React.

Rahul Jain
  • 369
  • 1
  • 13
1

You may need to setup React to accept many of the AMP directives using ReactInjection.

After you do it, the HTML produced by React will contain it.

import { DOMProperty } from 'react-dom/lib/ReactInjection'
DOMProperty.injectDOMPropertyConfig({
    Properties: {
        '[class]': DOMProperty.MUST_USE_PROPERTY
    }
})

UPDATE (AUG-25-2017):

The code above solves the case for regular HTML tags like div, ul, span, etc.

I'm currently having an issue placing [src] attribute inside a custom amp-list. React code does not take injected DOM Property into account for custom tags, the code considers that an attribute starting with '[' is not "safe" and remove it from the 'amp-list', regardless of the setup of injectDOMPropertyConfig.

There is a RFC for React 16 that would solve the issue: https://github.com/facebook/react/issues/10399

I have also placed a question on: https://github.com/facebook/react/pull/10385


Pedro Israel
  • 119
  • 5
  • Hi @PedroIsrael, that was some time again now, but did you ever figure out the issue with [src]? Thanks! – stubgo Mar 29 '18 at 06:09
0

Use the alternative syntax

<tag data-amp-bind-x="foo">

instead of

<tag [x]="foo">
Masih Jahangiri
  • 9,489
  • 3
  • 45
  • 51