简体   繁体   中英

Render to element inserted to DOM by jQuery

In my app I use AJAX to fetch a specific view (template) file and append it to the DOM using jQuery on page load:

$.get('/ajax/load/myview', function(view) {
    siteFetchComplete();
    $('#container').append(view);
});

There are various elements in the view that I would like to reference and render to using React . For example, to load a series of helpdesk tickets I might do something like:

function siteFetchComplete() {
    var TicketBox = React.createClass({
        render: function() {
            return (
                <h1>Helpdesk Tickets</h1>
            );
        }
    });

    React.render(
        <TicketBox />,
        $('#tickets')
    );
}

where $('#tickets') is an element that was appended after the AJAX request processed.

How do I reference $('#tickets') when calling React.render ? Currently I receive a Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element. error because React can't see the element when called this way.

You're passing a jQuery wrapper object to React instead of a DOM element. Instead you should unwrap it using jQuery's get() method and pass the raw DOM object to React:

$('#tickets').get(0) // returns the DOM element

Also move the call to siteFetchComplete() to after the append() operation, otherwise jQuery will be trying to find the element before it exists!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM