1
votes

I would like to render a simple list but it seems that react can't render unclosed pushed html elements. But it results an error

ReferenceError: el is not defined

if use simple quotes (')

bookingStatusList.push('<div className="select"><select id="department">');

The error is gone but the <div> and the <select> html is rendered as text and not html tags (the <option> are properly rendered)

enter image description here Here is my code

render()
    {
        const {bookingStatus} = this.state;
        const bookingStatusList = [];
        if(bookingStatus.length)
        {
            bookingStatusList.push(<div className="select"><select id="department">);
                bookingStatus.map(el => {
                bookingStatusList.push (
                    <option value={el.id} key={el.id}>
                        {el.name}
                    </option>
                )
            })
                bookingStatusList.push(</select></div>)
        }
        else
        {
            bookingStatusList.push('<div>LOADING</div>')
        }



        return (

            <div>

                        {bookingStatusList}

            </div>
        );
    }
2
What is el supposed to refer too?etarhan
bookingStatus.map(id => { change it to bookingStatus.map(el => {Vladimir Bogomolov
bookingStatus.map(id => { to bookingStatus.map(el => {Shibon
Yes , sorry i did a mistake on my code sample , the problem remainsLoic H

2 Answers

2
votes

JSX syntax looks like HTML, but it isn't HTML. It gets transpiled to JavaScript that explicitly creates elements and doesn't deal in tags.

So, no, you can't do it like that.

Turn your code inside out.

const list_of_options = bookingStatus.map(etc etc);
const div = <div><select>{list_of_options}</select></div>;
1
votes

Don't forgot, we write JSX not HTML, it will get transpiled into js. So you need to refactor you code little bit, Loop over the array and create all the options and then put that variable inside jsx.

Check Doc for more details.

Write it Like this:

render() {
    const { bookingStatus } = this.state;
    let bookingStatusList, options = [];

    if(bookingStatus.length) {
        bookingStatus.map(id => {
            options.push(
                <option value={el.id} key={el.id}>
                    {el.name}
                </option>
            )
        })
        bookingStatusList = (
            <div className="select">
                <select id="department">
                    {options}
                </select>
            </div>
        );
    }
    else {
        bookingStatusList = <div>LOADING</div>;
    }

    return (
        <div>
            {bookingStatusList}
        </div>
    );
}