I am working on project , where I am updating the url . Actually It working fine when I click on next button but I want to re-render application when function is invoked . I am new to ReactJS , Could some one please help me how to solve this problem .
I am sorry I am not native speaker , I am sorry if I made mistake in English grammer . Thanks
Displaying data through this URL Function
urlParams() {
return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&
filter[skip]=${this.state.skip}
&&filter[order]=${this.state.sortedData}`;
}
Full Component Code
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
Item: 5,
skip: 0
}
this.handleClick = this.handleClick.bind(this);
}
urlParams() {
return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
}
handleClick() {
this.setState({skip: this.state.skip + 1})
}
render() {
return (
<div>
<a href={this.urlParams()}>Example link</a>
<pre>{this.urlParams()}</pre>
<button onClick={this.handleClick}>Change link</button>
</div>
)
}
}
ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))
You can force a rerender of your component by calling:
this.forceUpdate();
However, you have to be careful not to enter a never-ending update cycle.
The usual (recommended) way to rerender is through the necessity of changing your state using setState.
EDIT
I think want you need is to call getData once you have clicked the table header:
getSortedData=()=>{
console.log("hello clicked")
this.setState({
sortedData:'companyName'
})
// now invoke getdata which will refresh the data:
this.getData()
}
Related
React
i have tried to make a button which will show how many times it is clicked using react state. but i want to do this with many component. So i wrote my state and update function with setState in a parent Component and want to pass the state as props, but the problem is as i pass the state once, then after the state is updated (when the button is clicked) the props dont update with that. and i cant see how many times the button is clicked.
class App extends Component {
constructor(props) {
super(props);
this.state = {
count: 2,
};
}
clickCount() {
this.setState((prev) => {
return { count: prev.count + 1 };
})
}
render() {
return (
<div>
<MainContent
handler={this.clickCount} totalCount={this.state.count}/>
</div>
);
}
}
export default App;
You seemed to have missed binding the function to this
class App extends Component {
constructor(props) {
super(props);
this.state = {
count: 2,
};
this.clickCount = this.clickCount.bind(this); // you may have missed this..
}
clickCount() {
this.setState((prev) => {
return { count: prev.count + 1 };
})
}
render() {
return (
<div>
<MainContent handler={this.clickCount} totalCount={this.state.count}/>
</div>
);
}
}
export default App;
I am currently using react-modal in my project and i have problem opening and closing it probably from other component.
class MainComponent {
constructor() {
this.state = {reportOpen: false};
}
closeReport = (e) => {
this.setState({reportOpen: false}, () =>
console.log(this.state.reportOpen)); // This line print true !!!
}
render() {
return (
<Button onClick={(e) => this.setState({reportOpen: true})}/>
<ReportModal isOpen={this.state.reportOpen} onClose= .
{this.closeReport}/>
)
}
}
// Modal
class ReportModal {
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.isOpen !== prevState.isOpen) {
return ({isOpen: nextProps.isOpen});
}
else {
return null;
}
}
render() {
return <Modal isOpen={this.state.isOpen}
onRequestClose={this.props.onClose}
shouldCloseOnOverlayClick={true}
shouldCloseOnEsc={true}/>
}
}
Due to the mentioned problem, I couldn't close the modal once i opened it. Please help me to figure out the problem here. Thanks for any help.
Missing extends React.Component in class declaration.
Missing super(props); call in constructor.
Please debug at getDerivedStateFromProps for the new derived state.
Also why don't you just handle the same in ReportModal component, the callback seems overwork
I am working on small react project, actually I have some problem regarding to function call. I am updating the value of URL and invoke the method through button click to display updated values but whenever I click the button first it give me old values when I click again it give me updated values. Could someone please help me how to avoid old values on first click, I want to show updated values on first click not on second click. I am new to ReactJS , Could someone please help me how to fix this problem?
Full Component Code
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
Item: 5,
skip: 0
}
this.handleClick = this.handleClick.bind(this);
}
urlParams() {
return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
}
handleClick() {
this.setState({skip: this.state.skip + 1})
}
render() {
return (
<div>
<a href={this.urlParams()}>Example link</a>
<pre>{this.urlParams()}</pre>
<button onClick={this.handleClick}>Change link</button>
</div>
)
}
}
ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))
State is not updating at time when urlParams is being called. As #jolly told you setState is Asynch function so it's better to use it in a callback or you may simply pass your sortedData type as in argument in getSortedType function instead of updating state. Also, ReactJS community suggests or the best practice is to use state only if props are needed to be updated.
In case, if you dont feel comfortable with CB. you may use setTimeOut which I think is a bad practice but it would solve your problem. your code would be like:
getSortedData=()=>{
this.setState({sortedData:'name desc'});
setTimeout(() => {
this.getData();
}, 200);
}
There's quite lots of code e no working example, so I may be wrong, but I think the problem is in getSortedData(): in that function, you call setState() and right after you call getData() which will perform a fetch, which uses ulrParams() function, which uses property this.state.sortedData.
The problem in this is that setState() is async, so it's not sure that, when urlParams() uses this.state.sortedData, the property is updated (actually, we are sure it's not updated).
Try to rewrite getSortedData() as follow:
getSortedData =() => {
this.setState({sortedData:'name desc'}, () => {
this.getData();
})
}
What I'm doing here is passing a callback to setState(): doing this way, getData() will be called AFTER you've updated the state.
Regarding the question you asked in the comment, if you want to toggle the order, you can add a property order in the state of the Component, assigning to it a default value 'name desc'.
Then, you change getSortedData as follow:
getSortedData =() => {
let newSort = 'name asc';
if (this.state.sorteData === newSort) 'name desc';
this.setState({sortedData: newSort}, () => {
this.getData();
})
}
I have written the following sample counter app using react.js. onClick fires the handleAddOne but the value of count never gets incremented.
class Counter extends React.Component {
constructor(props){
super(props);
this.handleAddOne = this.handleAddOne.bind(this);
this.state = {
count : 0
};
}
handleAddOne() {
console.log('handleAddOne');
this.state.count++;
}
render() {
return (
<div>
<h1>Count:{this.state.count}</h1>
<button onClick={this.handleAddOne}>+1</button>
</div>
);
}
}
ReactDOM.render(<Counter />, document.getElementById('app'));
In react, state is an immutable object, meaning you are supposed to set state values using only setStste function and not directly.
<button onClick={()=>{this.setState({count:this.state.count++})
}}>
+1
</button>
As the other answers suggest, you should be using setState to trigger the state change and rerender.
However, when using prevState it is also recommended that you use the functional version of setState
handleAddOne() {
console.log('handleAddOne');
this.setState(prevState=>({
count: prevState.count+1
}));
}
Documentation: https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly
I advise you to read more about Reactjs from https://reactjs.org/docs/hello-world.html
handleAddOne() {
console.log('handleAddOne');
this.setState({count: this.state.count++})
}
Hello guys I'm new to react
I'm working with react component passing a property from a state of parent component and I'm not sure why i get an undefined property error whenever i trigger and event from the parent component
You can visit the code here# https://codepen.io/private_ryan/pen/RVBdpO?editors=0011#live-view show console and click the edit button
SampleTable Component
constructor(props, context) {
super(props);
this.state = { UPD:[] };
}
updateRow(x) {
var array = this.state.TRs;
var index = array.findIndex(e => e.id == x);
this.setState({
UPD: this.state.TRs[index]
});
}
render() {
return (<AddFormData onAdd={ this.onAddForm }
upd={ this.state.UPD }
updcan={ this.cancelUpd }
propUpd= { this.propcessUpd } />
<button onClick={ this.updateRow} value={ some.id } >click me</button>
);
}
AddFormData Component
constructor(props) {
super(props);
this.state = { textName: '', textArea: '' };
}
componentWillReceiveProps(){
console.log( this.props ) // undefined no props when first click
// set the state here
}
New props are received as parameters to the function:
componentWillReceiveProps(nextProps)
https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops
componentWillReceiveProps will get called whenever you do any changes in props values in parent component, new values will get passed as parameter and after this lifecycle method this.props will get updated so if you do console.log(this.props) inside this it will log the previous value not the new one.
Use this:
componentWillReceiveProps(newProps){
console.log(this.props.upd.id, newProps)
}
Check the working example.