Nicolas Zozol
Nicolas Zozol

Reputation: 7038

React JS: HTML is rendered on screen

It must be an ultra basic. I want to make a very first demo, without using JSX to be more direct.

 const nicolas = {
    admin: true,
    id: 1,
    email: "[email protected]",
    name: "Nicolas",
    statement: "Star Wars rocks"
};

class User extends React.Component {
    render() {
        return React.createElement('div', null,
                `<div>name: ${this.props.name}</div>
                <div>statement: ${this.props.statement}</div>`
        );
    }
}

ReactDOM.render(
        React.createElement(User, nicolas, null),
        document.querySelector('section.app')
);

As a result, div tags are shown directly. Why ? and how to avoid that ? Must I use multiple imbricated React.createElement()

enter image description here

Upvotes: 2

Views: 61

Answers (2)

Nicolas Zozol
Nicolas Zozol

Reputation: 7038

React.createElement(root, props, elements) accept multiples elements, that can be strings.

const e = React.createElement;
class User extends React.Component {
    render() {
        return e('div', null,
            // strong for the whole line
            e('div', null,
                    e('strong', null, `name: ${this.props.name}`)
            ),
            // strong for left part only
            e('div', null,
                    e('strong', null, 'statement:'),
                    e('span', null, this.props.statement)
            )
    }
}

React.createElement Reference ; React Without JSX

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816322

Why ?

Because you are passing a string as a child to the element. The string is literally rendered into the document. It's the same as if you did:

<div>{'<span>something</span>'}</div>

in JSX, which is not the same as

<div><span>something</span></div>

How to avoid that ? Must I use multiple imbricated React.createElement()

Yes, every element needs to be created with React.createElement. There is a way to directly set HTML as content of an element, but you should avoid that.

Upvotes: 1

Related Questions