Home > OS >  Can I write HTML tags inside of a React code?
Can I write HTML tags inside of a React code?

Time:06-04

Sorry I'm newbie to React. It might be a stupid question but can I write HTML code inside of a React code? I'm trying to make a custom block for my wordpress theme and found a example code of JavaScript.

/* This section of the code registers a new block, sets an icon and a category, and indicates what type of fields it'll include. */
  
wp.blocks.registerBlockType('coin-info/border-box', {
    title: 'color-info',
    icon: 'money-alt',
    category: 'common',
    attributes: {
      content: {type: 'string'},
      color: {type: 'string'}
    },
    
  /* This configures how the content and color fields will work, and sets up the necessary elements */
    
    edit: function(props) {

      function updateContent(event) {
        props.setAttributes({content: event.target.value})
      }
      function updateColor(value) {
        props.setAttributes({color: value.hex})
      }
      return (
        "div",
        null,
        React.createElement(
          "h3",
          null,
          "Simple Box"
        ),
        React.createElement("input", { type: "text", value: props.attributes.content, onChange: updateContent }),
        React.createElement(wp.components.ColorPicker, { color: props.attributes.color, onChangeComplete: updateColor })
      );

    },
    
    save: function(props) {

      return wp.element.createElement(
        "h1",
        { style: { border: "3px solid "   props.attributes.color } },
        props.attributes.content
      );

    }
  })

I inserted some div tags and p tags inside of the code like HTML, but keeps giving me error. I think I need to study it later LOL

CodePudding user response:

Well, it is kind of tricky question. The problem that you cannot use HTML directly in React js files. To make things working you need to have a babel compiler that will replace you HTML tags with React objects.

The code you've sampled it using compiled code (React.createElement). You have to pass this data as a child of some react component to make it work.

So or you using enter link description here or use Babel compiler to prepare your code.

  • Related