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
Related
I have built a React component and I want to put data in it when the component loads but I constantly get the Array as empty. To my understanding if I have to put data in a component I should do so in ComponentDidMount method.
Below is my code.
var Home = React.createClass({
componentDidMount(){
console.log('component mount');
var self = this;
var str = "junk string";
$.ajax({
url: "http://localhost:9000/checkoutcart/data/",
type : "get",
data : {
ajaxid: 4,
UserID: str
},
}).then(function (data) {
self.setState({movieItem: data});
});
},
getInitialState: function() {
console.log('getInitialState component mount');
return {movieItem:[]};
},
render: function() {
return (
<div>
<div>
<div>
<ol>
{this.state.movieItem.map(stuff => (
<li><h4>{stuff.title}</h4></li>
))}
</ol>
</div>
</div>
</div>
);
}
});
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')
);
If I have a component:
var OuterComponent = React.createClass( {
render: function() {
return (
<div>
<MiddleComponent>
<Child parentFunctionShouldBe={this.middleComponentFunction} />
</MiddleComponent>
</div>
);
}
});
How do i pass the function that lives in the middle component? The issue is that this refers to the OuterComponent, not the MiddleComponent. I don't want it to be a static function, but an instance function.
Another option would be to use a Higher-order Component (HoC). This is a good choice if MiddleComponent is primarily adding markup around or capabilities to Child.
var MiddleComponent = function (Wrapped) {
var Component = React.createClass({
middleComponentFunction: function () {},
render: function () {
return (
<Wrapped {...this.props} parentFunctionShouldBe={this.middleComponentFunction} />
);
}
});
return Component;
}
var WrappedChild = MiddleComponent(Child);
var OuterComponent = React.createClass( {
render: function() {
return (
<div>
<WrappedChild passToChild="value" />
</div>
);
}
});
Further, you can customize how the integration occurs if you want to use MiddleComponent with other types of components.
var MiddleComponent = function (config, Wrapped) {
var prop = config.prop || 'parentFunctionShouldBe';
var Component = React.createClass({
middleComponentFunction: function () {},
render: function () {
var extraProps = {};
extraProps[prop] = this.middleComponentFunction;
return <Wrapped {...this.props} {...extraProps} />;
}
});
return Component;
}
// same result as above but configurable for other use cases
var WrappedChild = MiddleComponent({prop: 'parentFunctionShouldBe'}, Child);
var OuterComponent = React.createClass( {
render: function() {
return (
<div>
<WrappedChild passToChild="value" />
</div>
);
}
});
You can add a ref to a component, and call the method from the this.refs.componentRef:
var OuterComponent = React.createClass( {
callMethod: function() {
this.refs.middleComponent.middleComponentFunction();
},
render: function() {
return (
<div>
<MiddleComponent ref="middleComponent">
<Child parentFunctionShouldBe={this.callMethod} />
</MiddleComponent>
</div>
);
}
});
You can do something like this
var OuterComponent = React.createClass( {
render: function() {
return (
<div>
<MiddleComponent>
<Child />
</MiddleComponent>
</div>
);
}
});
var MiddleComponent = React.createClass({
propTypes: {
children: React.PropTypes.element.isRequired
},
render: function() {
return (
<div>
{React.cloneElement(this.props.children, {parentFunctionShouldBe: this.middleComponentFunction})}
</div>
)
},
middleComponentFunction: function() {
...
}
});
I am using meteor-react, kadira:flowrouter and kadira:react-layout with remove autopublish and insecure and I get
Uncaught TypeError: Cannot read property 'map' of undefined
React's render function execute first before the subscribe is done receiving the data from mongoDB. How do I let the data load first before render execute?
Store = React.createClass({
mixins: [ReactMeteorData],
getMeteorData() {
var coursesFetch
Meteor.subscribe("getAllCourses", () => {
coursesFetch = Courses.find().fetch()
console.log(coursesFetch);
})
return {
courses: coursesFetch
}
},
render() {
let displayCourses = this.data.courses.map((data) => {
return (
<StoreItemButton key={data._id} title={data.title} description={data.description}/>
)
})
return (
<div className="container-fluid">
<div className="card-columns">
{displayCourses}
</div>
</div>
)
}
})
I just figure it out by adding subscriptions function to my FlowRouter.
router.jsx
FlowRouter.route("/store", {
name: "Store",
subscriptions: function() {
this.register('getAllCourses', Meteor.subscribe('getAllCourses'));
},
action (params) {
renderMainLayoutWith(<Store/>)
}
})
Store.jsx
Store = React.createClass({
mixins: [ReactMeteorData],
getMeteorData() {
return {
courses: Courses.find().fetch()
}
},
render() {
let displayCourses = this.data.courses.map((data) => {
return (
<StoreItemButton key={data._id} title={data.title} description={data.description}/>
)
})
return (
<div className="container-fluid">
<div className="card-columns">
{displayCourses}
</div>
</div>
)
}
})
Currently i m working on creating react components, and i need to repeat the child components, based on this.props.value of parent component.
I am struggling to find any good examples.
here is my code
var LiComponent = React.createClass({
render:function(){
return(
<div>
<span>{this.props.label}</span>
<span>{this.props.value}</span>
</div>
);
}
});
var StatsComponent = React.createClass({
getInitialState: function(){
return{
value: this.props.value || []
}
},
componentDidMount: function(){
var data = this.state.value,
columnName = data[0],
data = data.slice(1),
values = data.map(function (o) { return o.value; }),
labels = data.map(function (o) { return o.label; });
},
shouldComponentUpdate: function(nextProps, nextState){
var data = nextProps.value,
labels = data.map(function (o) { return o.label; }),
values = data.map(function (o) { return o.value; });
return false;
},
render: function(){
return (
<div style={style}>
<LiComponent>
</LiComponent>
</div>
);
}
});
now, i want to repeat the LiComponent according to the this.props.value of Stats Component. How should i do that?
You can push LiComponents to an array, and render these.
Like this,
render: function(){
var rows = this.props.value.map(function(row) {
//Add props to your LiComponent just as you would normally.
return <LiComponent />;
});
return (
<div style={style}>
{rows}
</div>
);
}