React - Load Initial List via AJAX - javascript

I'm starting to learn react. There's an excellent example in the official docs about loading data initially via AJAX:
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
The code above gets the latest gist of a specific user from GitHub.
What is the best way in React to go about outputting a list of the last 10 gists of the specific user?
How would you modify the code sample above?

var UserGist = React.createClass({
getInitialState: function() {
return {
gists: []
};
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
this.setState({
gists: result
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return <div>
{this.state.gists.map(function(gist){
return <div key={gist.id}>{gist.owner.login}</div>
})}
<div>;
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);

Related

ReactJS - moving list items between components

I am trying to create two components, one that holds the results of an API call from iTunes. I want to be able to click on any one of the items and move it to the empty component, moveResults, and then move it back to searchResults if it is clicked again. From other exercises, I feel like I am close, however I keep getting an error about the this.handleEvent = this.handleEvent.bind(this). Any ideas as to where I might have gone wrong and some possible solutions?
var App = React.createClass({
getInitialState: function() {
return {
searchResults: [],
moveResults: []
}
},
this.handleEvent = this.handleEvent.bind(this);
showResults: function(response) {
this.setState({
searchResults: response.results,
moveResults: []
})
},
search: function(URL) {
$.ajax({
type: 'GET',
dataType: 'json',
url: URL,
success: function(response) {
this.showResults(response);
}.bind(this)
});
},
handleEvent(trackId) {
const isInSearchResults = this.state.searchResults.includes(trackId);
this.setState({
searchResults: isInSearchResults ? this.state.searchResults.filter(i => i !== trackId) : [...this.state.searchResults, trackId],
moveResults: isInSearchResults ? [...this.state.moveResults, trackId] : this.state.moveResults.filter(i => i !== trackId)
});
},
componentDidMount() {
this.search('https://itunes.apple.com/search?term=broods')
},
render: function(){
return (
<div>
<Results searchResults={this.state.searchResults} handleEvent={this.handleEvent}/>
<Results searchResults={this.state.moveResults} handleEvent={this.handleEvent} />
</div>
);
}
});
var Results = React.createClass({
render: function(){
let handleEvent = this.props.handleEvent;
var resultItems = this.props.searchResults.map(function(result) {
return <ResultItem key={result.trackId} trackName={result.trackName} onClick={() => handleEvent(resultItems.id)} />
});
return(
<ul>
{resultItems}
</ul>
);
}
});
var ResultItem = React.createClass({
render: function(){
return <li> {this.props.trackName} </li>;
}
});
ReactDOM.render(
<App />, document.getElementById('root')
);

ReactJs - getInitialState not working

I'm playing with ReactJs, and i have this simple code
var User = React.createClass({
render: function () {
return(
<li>
{this.props.email}
</li>
);
}
});
var UserList = React.createClass({
reload: function () {
var xhr = new XMLHttpRequest();
xhr.open('get', "http://localhost:64501/Home/GetUsers", true);
xhr.onload = function () {
var result = JSON.parse(xhr.responseText);
this.setState({ data: result });
console.log(JSON.stringify(result));
}.bind(this);
xhr.send();
},
getInitialState: function () {
return {
data: [
{ email: "bob#gmail.com", id: "1" },
{ email: "boby#gmail.com", id: "2" }
]
};
},
componentDidMount: function () {
window.setInterval(this.reload, 3000);
},
render: function () {
if (this.props.data != null) {
var userNodes = this.props.data.map(function (user) {
return (
<User email={user.email} key={user.id } ></User>
);
});
return (
<div>
<ul>{userNodes}</ul>
</div>
);
}
else {
console.log("this.props.data is null");
return null;
}
}
});
ReactDOM.render(<UserList />, document.getElementById('root'));
I got 2 issues :
1 - the datas returned by getInitialState function are not rendered by the component.
2 - setState does not refresh the component in the reload function.
You are reading this.props.data and you should be reading this.state.data.
Note the difference between component properties, which come externally, and component internal state.
Just replace all this.props.data with this.state.data and your code should work.

Unable to render json data in ReactJS components

I am trying to show data from package.json in my ReactJS components. I have seen many answers on SO and tried to implement it. It is neither showing any data nor an error.
This is package.json:
{
"name":"Clark Kent",
"job":"Superman"
}
This is my jsx:
var App = React.createClass({
getInitialState: function(){
return { myData: [] };
},
showResults: function(response){
this.setState({
myData: response
});
},
loadData: function(URL) {
var that = this;
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: URL,
success: function(response){
that.showResults(response);
}
})
},
componentDidMount: function() {
this.loadData("package.json");
},
render: function(){
return(
<div>
<Component1 data={this.state.myData} />
<Component2 data={this.state.myData}/>
</div>
)
}
});
var Component1 = React.createClass({
render: function () {
return(
<div>Name: {this.props.data.name}</div>
)
}
});
var Component2 = React.createClass({
render: function () {
return(
<div>Job: {this.props.data.job}</div>
)
}
});
ReactDOM.render(<App/>, document.getElementById('container'));

load json with reactjs

I'll be very grateful who can help me with this line
I've this:
var Country = React.createClass({
render:function(){
return(
<nav>
<h2>list of country:</h2>
{ this.props.country}
</nav>
)
}
})
var Jugador =React.createClass({
componentWillMount: function(){
var pais;
var self = this;
$.getJSON("https://restcountries.eu/rest/v1/all", function(data){
for(pais in data)
{
console.log(pais, data[pais].name);
return(
<Country key={i} country={self.render(data[pais].name)}> </Country>
)
}
})
},
})
and it does not work, and appear this error
Uncaught Invariant Violation: createClass(...): Class specification must implement a render method.
Your Jugador component needs to implement a render method.
In React each component must have render method, you should implement it. I've refactored your code and now it look like this
var Country = React.createClass({
render: function() {
return <div>
{ this.props.country }
</div>
}
})
var Countries = React.createClass({
getInitialState: function () {
return { countries: [] };
},
componentWillMount: function(){
$.getJSON("https://restcountries.eu/rest/v1/all", function (data) {
this.setState({ countries: data })
}.bind(this))
},
render: function () {
var countries = this.state.countries.map(function (el, i) {
return <Country key={i} country={ el.name } />
}, this);
return <nav>
<h2>list of country:</h2>
<div>{ countries }</div>
</nav>;
}
})
Example

React DnD in a Meteor app

I am using react with my meteor app and I need to integrate this with a list of items.
There is a ItemList.jsx and a ItemRow.jsx since the item itself has text, links, images, ect.
ItemRow.jsx
ItemRow = ReactMeteor.createClass({
templateName: "ItemRow",
propTypes: {
item: React.PropTypes.object.isRequired,
showPoolTitle: React.PropTypes.bool,
},
getInitialState: function() {
return {
editing: false,
drop: this.props.item,
pool: {},
}
},
startMeteorSubscriptions: function() {
Meteor.subscribe("ItemRow", this.props.item._id);
},
getMeteorState: function() {
return {
item: Items.findOne(this.props.item._id),
pool: Pools.findOne(this.props.drop.poolId),
};
},
toggleEditing: function() {
this.setState({ editing: !this.state.editing });
},
render: function() {
var content;
if (this.state.editing) {
content = <ItemRowEdit drop={this.state.item} done={this.toggleEditing}/>
} else {
content = <ItemRowShow pool={this.state.pool} item={this.state.item} edit={this.toggleEditing} showPoolTitle={this.props.showPoolTitle}/>
}
return (
<div key={this.props.item._id} className="item">
{content}
</div>
)
},
});
and ItemList.jsx
ItemList = ReactMeteor.createClass({
templateName: "ItemList",
propTypes: {
items: React.PropTypes.object.isRequired
},
getInitialState: function() {
return {
items: this.props.items.fetch()
}
},
render: function() {
var items = this.state.items;
return (
<div className="ui very relaxed huge list">
{items.map(function(item) {
return ( <ItemRow item={item}/> );
})}
</div>
);
}
});
I am not using Meteor react for ItemList just yet but I want to be able to drag and drop reorder first so any help to get me on the right track is much appreciated!

Categories