I'm new to ReactJS. I need to show a text as many times as user clicks. I have tried but some how it is not working as expected. Please help.
var Paragraph = React.createClass({
renderParagraph: function(){
for(i=0; i<this.props.data;i++){
<p key={i}> Hello World </p>
}
},
render: function() {
return(
<div>
{this.renderParagraph}
</div>
);
}
});
var Container = React.createClass({
getInitialState: function() {
return {
counter: 0
}
},
increment: function() {
this.setState({
counter: this.state.counter + 1
});
},
render: function() {
return (
<div className="well">
<Paragraph data={this.state.counter}/>
<button className="btn btn-primary" onClick={this.increment}> Increase Me
</button>
</div>
)
}
});
React.render(<Container />, document.getElementById('root'));
In the above code, i'm trying to render Paragraph component as many times as user clicks.
Implementation here: http://jsbin.com/jevufu/edit?js,output
Thanks in advance.
You need call method this.renderParagraph() not just pass reference this.renderParagraph., also, from method renderParagraph you need return array with Nodes,
var Paragraph = React.createClass({
renderParagraph: function() {
var paragraphs = [];
for (var i = 0; i < this.props.data; i++) {
paragraphs.push(<p key={i}> Hello World { i } </p>);
}
return paragraphs;
},
render: function() {
return(
<div>{ this.renderParagraph() }</div>
);
}
});
Example
Related
I am tring to show todo list with load more option. I am appling limit.Limit is apply to list.But when i add loadmore()function. then i get error this.state.limit is null Wher i am wrong.Any one can suggest me.
here is my code
todoList.jsx
var TodoList=React.createClass({
render:function(){
var {todos}=this.props;
var limit = 5;
function onLoadMore() {
this.setState({
limit: this.state.limit + 5
});
}
var renderTodos=()=>{
return todos.slice(0,this.state.limit).map((todo)=>{
return(
<Todo key={todo.todo_id}{...todo} onToggle={this.props.onToggle}/>
);
});
};
return(
<div>
{renderTodos()}
<a href="#" onClick={this.onLoadMore}>Load</a>
</div>
)
}
});
module.exports=TodoList;
Changes:
1. First define the limit in state variable by using getInitialState method, you didn't define the limit, that's why this.state.limit is null.
2. Define all the functions outside of the render method.
3. Arrow function with renderTodos is not required.
4. Use this keyword to call the renderTodos method like this:
{this.renderTodos()}
Write it like this:
var TodoList=React.createClass({
getInitialState: function(){
return {
limit: 5
}
},
onLoadMore() {
this.setState({
limit: this.state.limit + 5
});
},
renderTodos: function(){
return todos.slice(0,this.state.limit).map((todo)=>{
return(
<Todo key={todo.todo_id}{...todo} onToggle={this.props.onToggle}/>
);
});
};
render:function(){
var {todos} = this.props;
return(
<div>
{this.renderTodos()}
<a href="#" onClick={this.onLoadMore}>Load</a>
</div>
)
}
});
This is witout button click.
As you all know react components has a function componentDidMount() which gets called automatically when the template of that component is rendered into the DOM. And I have used the same function to add the event listener for scroll into our div iScroll.
The scrollTop property of the element will find the scroll position and add it with the clientHeight property.
Next, the if condition will check the addition of these two properties is greater or equal to the scroll-bar height or not. If the condition is true the loadMoreItems function will run.
class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
items: 10,
loadingState: false
};
}
componentDidMount() {
this.refs.iScroll.addEventListener("scroll", () => {
if (this.refs.iScroll.scrollTop + this.refs.iScroll.clientHeight >=this.refs.iScroll.scrollHeight){
this.loadMoreItems();
}
});
}
displayItems() {
var items = [];
for (var i = 0; i < this.state.items; i++) {
items.push(<li key={i}>Item {i}</li>);
}
return items;
}
loadMoreItems() {
this.setState({ loadingState: true });
setTimeout(() => {
this.setState({ items: this.state.items + 10, loadingState: false });
}, 3000);
}
render() {
return (
<div ref="iScroll" style={{ height: "200px", overflow: "auto" }}>
<ul>
{this.displayItems()}
</ul>
{this.state.loadingState ? <p className="loading"> loading More Items..</p> : ""}
</div>
);
}
}
This is example
I have recently started to learn react and maybe i do not fully understand how it should work.
I have created a react script
var Parent = React.createClass({
getInitialState: function() {
return {children: []};
},
onClick: function() {
var childrens = this.state.children;
childrens.push({
name: this.props.name,
index: this.state.children.length + 1,
key: this.props.name + this.state.children.length + 1
});
this.setState({children: childrens});
},
onChildMinus: function(index) {
var childrens = this.state.children;
childrens.splice(index - 1, 1);
this.setState({children: childrens});
},
render: function() {
return (
<div>
<div className="parent" onClick={this.onClick}>
{this.props.name}
- Click Me
</div>
{this.state.children.map((child) => (<Child name={child.name} index={child.index} key={child.key} onMinusClick={this.onChildMinus}/>))}
</div>
);
}
});
var Child = React.createClass({
getInitialState: function() {
return {selected: false};
},
onClick: function() {
this.setState({selected: true});
},
onMinusClick: function() {
if (typeof this.props.onMinusClick === 'function') {
this.props.onMinusClick(this.props.index);
}
},
render: function() {
let classes = classNames({'child': true, 'selected': this.state.selected});
return (
<div className={classes}>
<span onClick={this.onClick}>{this.props.name} {this.props.index}</span>
<span onClick={this.onMinusClick}>Remove</span>
</div>
)
}
});
ReactDOM.render(
<Parent name="test"/>, document.querySelector("#container"));
https://jsfiddle.net/uqcxo1pg/1/
It is a button that when you click it, it creates a child element that has a number, there is a delete button on the child element.
When you delete the child element it remove it from the parent array, but how do it make it so that it updates all of the child elements to now have the correct number?
Because you're setting the index of the child in onClick, that value is never update when a prior child is removed. If the purpose of index on <Child/> is just for numbering, you can pass the index of the child in the array instead of the index assigned in onClick. If you need both the original index and the order, I'd suggest adding another prop to <Child />.
{this.state.children.map((child, index) => (
<Child
name={child.name}
index={index}
key={child.key}
onMinusClick={this.onChildMinus}
/>
))}
https://jsfiddle.net/uqcxo1pg/2/
Update
Alternatively, if you need child.index to be updated, you'll have to iterate over this.state.children and renumber them. The most efficient way would be to start at the index of the removed child but this is the brute force alternative.
const renumberedChildren = this.state.children.map((child, index) => {
child.index = index + 1;
return child;
});
When switching data by selecting slice from an array, putting it into state and rendering by setInterval, I try to create a slider effect by clicking up and down arrows:
UPDATE START
I was finally able to create slider using technique from this codepen:
http://codepen.io/sergiodxa/pen/aOYdeN
UPDATE END
var MainContainer = React.createClass({
getInitialState: function () {
return {
position: 0,
max_elements: 3,
data: [],
source: Array.prototype.slice.call([1, 2, 3, 4, 5, 6, 7]).reverse()
}
},
componentDidMount: function () {
setInterval(this.updateState, 10);
},
arrowUp: function () {
if (this.state.position > 0) {
this.state.position--;
this.updateState();
}
},
arrowDown: function () {
if (this.state.source.length - this.state.position > this.state.max_elements) {
this.state.position++;
this.updateState();
}
},
updateState: function () {
data = this.state.source.slice(this.state.position, this.state.position + this.state.max_elements)
this.setState({data: data});
console.log(this.state.data);
},
render: function () {
var Items = this.state.data.map(function (item, i) {
return (
<div key={i}>
<SimpleItem message={item} active={i == 0 ? true : false}/>
</div>
);
}, this);
return (
<div>
{Items}
<ArrowUp onClick={this.arrowUp}/>
<ArrowDown onClick={this.arrowDown}/>
</div>
);
}
});
var ArrowUp = React.createClass({
render: function () {
return (
<a href="#" className="glyphicon glyphicon-arrow-up" onClick={this.props.onClick}>
</a>
);
}
});
var ArrowDown = React.createClass({
render: function () {
return (
<a href="#" className="glyphicon glyphicon-arrow-down" onClick={this.props.onClick}>
</a>
);
}
});
var SimpleItem = React.createClass({
render: function () {
var className = "well well-lg"
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
className = this.props.active ? className + " active" : className;
return (
<ReactCSSTransitionGroup
transitionName="example"
transitionAppear={true} transitionAppearTimeout={500}
transitionEnter={false} transitionLeave={false}
>
<div className={className}>
{this.props.message}
</div>
</ReactCSSTransitionGroup>
);
}
});
ReactDOM.render(<MainContainer />, document.getElementById('container'));
The animation is only seen when components render for the first time, re-rendered elements won't animate, for some reason.
My styles are:
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity 500ms ease-in;
}
I'm not a frontend guy so any hint or link would be much appreciated.
I noticed a couple of things wrong. This first is in you arrowUp and down functions. State always needs to be set using the setState() function. From the docs:
NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
The second thing is that the children of ReactTransition group must have a unique key. When this key changes that is what tells react transition group to animate.
<ReactCSSTransitionGroup
transitionName="example"
transitionAppear={true} transitionAppearTimeout={500}
transitionEnter={false} transitionLeave={false}
>
{*/ This div needs a key. When the key changes react transition group animates. /*}
<div key={this.state.currentItem} className={className}>
{this.props.message}
</div>
</ReactCSSTransitionGroup>
In the above example I've set the key to this.state.currentItem your up and down arrow functions would update state.currentItem appropriately, react would re-render the component, react transition group would animate because this.state.currentItem changed.
I've made this "Currency-Converter" to get an idea of how React works.
It works (more or less) but the result is shown with an offset:
You type "1" (Euro) => It shows "0 Dollar".
You type "10" => It shows "1.1308 Dollar".
You type "100" => It shows "11.308 Dollar".
...
var Display = React.createClass({
render: function() {
return (
<div>
<p>{this.props.euro + ' Euro are equal to ' + this.props.dollar + ' Dollar.'}</p>
</div>
)
}
});
var Converter = React.createClass({
getInitialState: function() {
return { euro: 0, dollar: 0, exchangeRate: 1.1308 }
},
convertEuroToDollar: function() {
this.setState({ euro: +document.querySelector('#amount-euro').value });
this.setState({ dollar: this.state.euro * this.state.exchangeRate });
},
render: function() {
return (
<div>
<input type="text" id="amount-euro" onKeyUp={this.convertEuroToDollar} />
<Display dollar={this.state.dollar} euro={this.state.euro} exchangeRate={this.state.exchangeRate} />
</div>
)
}
});
ReactDOM.render(
<Converter />,
document.querySelector('#app')
);
div {
margin: 30px 50px;
}
<div id="app"></div>
Live-Demo on CodePen: http://codepen.io/mizech/pen/vGbJxe
It should display the result (euro * exchangeRate) at once.
What I'm doing wrong here?
Calling two setStates one after all, you wasn't setting the euro state properly.
Being async, you was still using the old value of it.
From the docs:
setState() does not immediately mutate this.state but creates a
pending state transition. Accessing this.state after calling this
method can potentially return the existing value.
https://facebook.github.io/react/docs/component-api.html
To fix the problem, do:
convertEuroToDollar: function() {
const euro = +document.querySelector('#amount-euro').value
this.setState({
euro: euro,
dollar: euro * this.state.exchangeRate
});
},
Fixed example: http://codepen.io/FezVrasta/pen/xVeMMX
Second problem I see, it would be much better to use ref instead of document.querySelector.
convertEuroToDollar: function() {
const euro = +this.refs.amountEuro.value;
this.setState({
euro: euro,
dollar: euro * this.state.exchangeRate
});
},
render: function() {
return (
<div>
<input type="text" ref="amountEuro" onKeyUp={this.convertEuroToDollar} />
<Display dollar={this.state.dollar} euro={this.state.euro} exchangeRate={this.state.exchangeRate} />
</div>
)
}
I am very new to React and am just getting my feet wet. I'm having a hard time understand why this isn't re-rending the List. Here is my code:
app.jsx
var Hello = React.createClass({
getInitialState: function() {
return {
links: ['test ']
}
},
render: function() {
return <div className = "row">
<Submission linkStore = {this.state.links}/>
<List links = {this.state.links} />
</div>
}
});
var element = React.createElement(Hello, {});
ReactDOM.render(element, document.querySelector('.container'));
In my submission.jsx I have this function to push info into the links array
handleSubmitClick: function() {
this.props.linkStore.push(this.props.text)
this.setState({text: ''})
console.log(this.props.linkStore)
}
My list.jsx looks like this
module.exports = React.createClass({
getInitialState: function() {
return {
links: this.props.links
}
},
render: function() {
return <div>
{this.props.links}
</div>
}
});
Everything works as intended and I can get the test to show appropriately.
I am aware that this isn't going to show up as an actual list and that I should create a list component to show the items in list form. I'm just trying to run tests along the way to see how everything works.
Use parent state instead of child props.
try this
app.jsx
var Hello = React.createClass({
getInitialState: function() {
return {
links: ['test ']
}
},
handleListSubmitClick: function(params) {
this.setState({links:params});
},
render: function() {
return <div className = "row">
<Submission linkStore = {this.state.links} handleListSubmitClick={this.handleListSubmitClick}/>
<List links = {this.state.links} />
</div>
}
});
submission.jsx
handleSubmitClick: function() {
var linkStore = this.props.linkStore;
linkStore.push(this.props.text)
this.setState({text: ''})
this.props.handleListSubmitClick(linkStore);
}
but I don't understand this.props.text. input's value using this.refs.ref
list.jsx
module.exports = React.createClass({
getInitialState: function() {
return {
links: this.props.links
}
},
render: function() {
return <div>
{this.props.links}
</div>
}
});