Hitesh Upadhyay
Hitesh Upadhyay

Reputation: 91

Ajax call in React stateless component

I have one react stateless component and its inner html would be dynamic.

So I had tried to get ajax data and set it as html. but it is just behaving like plain html (means new html contains other react components. but those are not compiling as react component).

So, Is there any way to get html from ajax call and set it to React stateless component with compiling it as react component?


More detail As per request of @Gosha Arinich:

Basically i want to make popup functionality. So, main popup component will carry outer structure, header and footer of popup. and content of different popups will set in other files, and i want to get ajax of requested file and set it as html into popup body.

import React, { PropTypes } from 'react';

function getDataFromFile(filename){
   $.get(filename, function (result) {
       document.getElementById("content").innerHTML = result;
   })
}

const Popup = ({filename}) => {
   getDataFromFile(filename);

    return (
        <div className="popup-container">
            <PopupHeader />
            <div id="content"></div>
            <PopupFooter />
        </div>
    );
};

// prop validation
Popup.propTypes = {
    filename: PropTypes.string.isRequired
};

export default Popup;

Upvotes: 2

Views: 2465

Answers (1)

Dennis Shtatnov
Dennis Shtatnov

Reputation: 1363

No, stateless components should not be able to dynamically change themselves. You can use jquery to hack changes into the component, but this is not recommended, as what is rendered by a stateless component should only be a product of its props.

The best practice solution is to wrap it:

var ParentComponent = React.createClass({

    getInitialState: function(){ return {html: null}; }
    componentWillMount: function(){
        // Do ajax call instead of timeout
        setTimeout(function(){
            this.setState({html: 'abcd'});
        }.bind(this))
    },

    render: function(){
        return (
            <div>
                   <OtherReactComponentsHere/>
                   {this.state.html? <StatelessChild html={this.state.html} /> : <span>Loading...</span>}
            </div>
        );
    }
})

The render function of StatelessChild would look like:

render: function(){
    return <span dangerouslySetInnerHTML={{__html: this.props.html}}></span>
}

Upvotes: 1

Related Questions