(React) dynamic component conditional setstate

react setstate
react setstate callback
react setstate function
react, ( usestate)
react hooks
componentdidmount setstate
react update state
react setstate not updating

I'm trying to create a dynamic component that matches the data index with the URL parameter blogID I get with the with the router.

Here I have the router parameters and send the props to the component

<Route path='/blog/:blogId/:blogTitle' render={() => <BlogPost blogData={this.state.blogData} /> }  />     

then on the component I set the initial state and I try to render the data that matches the index of the data, but I get an error of component repeatedly calling setstate and infinite loops.

constructor(props){
        super(props);
        this.state = {
            blogId:'',
            blogTitle:'',
            blogData:[]
        }            
    }   
   render(){                  
        const { params:{ blogId, blogTitle } } = this.props.match;  

// so i map here to get the index and set the conditional to set the new state but I don't know where or how exactly        

        this.props.blogData.map((val, idx) => ( 
            idx == blogId ? 
                this.setState({blogData:val }) : null                               
        ))
        return (                          
          <div>              


           <BlogView title={this.state.blogData.title} />


          </div>
        )  
    } 

You shouldn't setState inside render() function, the reason is that when you set state, compoennt needs to re-render to show user the updated data and then re-render again and again, instead do it in componentDidMount lifeCycle method so that it will run only once

componentDidMount() {
  const { params:{ blogId, blogTitle } } = this.props.match;  
  this.props.blogData.map((val, idx) => ( 
    idx == blogId ? 
    this.setState({blogData:val }) : null                               
  ))
}

How to become a pro with React setState() in 10 minutes, Of course, application UIs are dynamic and change over time. That's why state was created. State allows React components to change their  Consider we have a component, and based on a boolean flag we want to show or hide a paragraph <p> Below is a small component which receives props having book name and author name. Lets not concentrate on how the whole app works. We want to focus on conditional rendering.


The reason you are getting an infinite loop that is calling a setState in your render method, which causes a re-render, which causes a setState, which causes re-render...so on.

Try moving this part out of the render method.

this.props.blogData.map((val, idx) => ( idx == blogId ? this.setState({blogData:val }) : null ))

State and Lifecycle – React, State and Lifecycle. This page introduces the concept of state and lifecycle in a React component. setState() to schedule updates to the component local state:. When I first started learning JavaScript, I was confused about exactly what line 3 above what trying to accomplish. I knew that changing an input field created an event object and that line 2 was…


If you call setState in the render like this, you will cause infinite loops.

You don't need to setState once you find the blog, just use its title in BlogView after a find:

render() {                  
    const { params:{ blogId, blogTitle } } = this.props.match;        

    const blog = this.props.blogData.find((val, idx) => idx === blogId);
    return (                          
        <div>
            <BlogView title={blog.title} />
        </div>
        );  
} 

How to Show and Hide ReactJS Components, Everything in the React app is a component, so we have to play around components most of To show or hide any component using any condition, we should have the values, and setState({ showHideDemo1: !this.state. Here’s a good article about optimizing conditional rendering in React — I totally recommend you read it. The essential idea is that changing the position of the components due to conditional rendering can cause a reflow that will unmount/mount the components of the app. Based on the example of the article, I created two JSFiddles.


Add a conditional block before calling the set state inside render. if the both values are same, don't call the set state.

   render(){                  
        const { params:{ blogId, blogTitle } } = this.props.match;  

// so i map here to get the index and set the conditional to set the new state but I don't know where or how exactly        

        this.props.blogData.map((val, idx) => ( 
            (idx == blogId && val != this.state.blogData) ? 
                this.setState({blogData:val }) : null                               
        ))
        return (                          
          <div>              


           <BlogView title={this.state.blogData.title} />


          </div>
        )  
    } 

How to Pass Props Object from Child Component to Parent , Below is an example of a basic React component: we would want to have component display dynamic data instead of static data. setState(state => ({ isDisplayed: !state. This is how conditional rendering works in React. Inside it, the Clock component schedules a UI update by calling setState () with an object containing the current time. Thanks to the setState () call, React knows the state has changed, and calls the render () method again to learn what should be on the screen.


Yes I finally did it,

I set the state on the componentDidMount()

componentDidMount(){                        
  const { params:{ blogId, blogTitle } } = this.props.match;           
  this.setState({blogId, blogTitle});
} 

and the comparison on the render and it worked perfect

const blogger =  this.props.blogData.map((val, idx) => (             
            idx == this.state.blogId ?
                <BlogView 
                    title={val.title}
                    body={parse(val.body)}
                    img={val.thumb}
                />
                : null            
        )) 

React Patterns, If we plan to use this condition a lot, we can define another components to encapsulate the reused logic. const MinWidth = ({ width: minWidth, children }) => ( <  In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application. Conditional rendering in React works the same way conditions work in JavaScript.


If-Else in JSX, Interactivity and Dynamic UIs · Multiple Components · Reusable Components This is because JSX is just syntactic sugar for function calls and object construction. This JSX: <div id={if (condition) { 'msg' }}>Hello World! you can use if statements outside of your JSX to determine which components should be used:. How to pass data between React Components; Advance Of React JS. Components Lifecycle in React JS; Components In React Js; How to Create a Login Form in React JS; The conditional operator in React JS; How to call a Child Component on click of a button; How to use bootstrap in React JS; Todo List Application in React; Create a Dynamic Table


React: Use a Ternary Expression for Conditional Rendering , Before moving on to dynamic rendering techniques, there's one last way to use Within the component's return statement, set up a ternary expression that  npx create-react-app react-fundamentals Named exports V/S Default exports If a component is exported as named export , then it should be imported inside a brace with the exact same name.


Loading React Components Dynamically on Demand, setState . It is because to make component sorting easier later in render() (I'd appreciate it if anyone let me know instantiating here instead of in  setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.