JSP749 JSP749 - 1 month ago 25
Javascript Question

Calling React JS from jsp

I am new to React, and I'm making a webpage to show a list of items.

I have this React Code in a file called admins.js:

//more code

var AdminsBox = React.createClass({
getInitialState: function() {
return {adminsList: []};
},
setAdminsArray: function(data) {
this.setState({adminsList: data});
},
render: function() {

return (
<div>
<AdminsContentBox adminsList={this.state.adminsList}/>
</div>
);
}});

var AdminsBoxRender = ReactDOM.render(
<AdminsBox />,
document.getElementById('adminsContent')
);


And in the file index.jsp:

<html lang="es">
<head>
<link rel="stylesheet" href="base.css" />
<script src="react.js"></script>
<script src="react-dom.js"></script>
<script src="browser.js" charset="utf-8"></script>
<script src="jquery.min.js"></script>
<script src="marked.min.js"></script>

<link rel="stylesheet" href="fonts.css">
<link rel="stylesheet" href="material.indigo-blue.min.css">

<script type="text/babel" src="admins.js"></script>

<script>
$(document).ready(function() {
$.ajax({
url: 'myUrlServlet',
type: 'POST',
data: "function=getAdmins",
dataType: "json",
success: function(data){
AdminsBoxRender.setAdminsArray(data);
}
});
});
</script>
</head>


<body>
<div id="adminsContent"></div>
</body>


The error I get is AdminsBoxRender is not defined.

What am I doing wrong?

Thank you in advance.

QoP QoP
Answer

That's not the proper way to fetch data for your component, you should fetch it in componentDidMount()

var AdminsBox = React.createClass({
    getInitialState: function() {
        return {adminsList: []};
    },
    componentDidMount: function(){
         $.ajax({
                url: 'myUrlServlet',
                type: 'POST',
                data: "function=getAdmins",
                dataType: "json",
                success: function(data){
                    this.setState({adminsList: data});
                }
            });
    },
    setAdminsArray: function(data) {
        this.setState({adminsList: data});
    },
    render: function() {

        return (
            <div>
                <AdminsContentBox adminsList={this.state.adminsList}/>
            </div>
        );
}});


window.AdminsBoxRender = ReactDOM.render(
    <AdminsBox />,
    document.getElementById('adminsContent')
);

You should keep the stuff related to React "inside" React.