Luis García
Luis García

Reputation: 53

Is it possible to use conditional rendering of a React component when a variable is undefined?

My ecommerce project has a "ProductPage" component which displays product information like price, color, size, etc.

The component gets the product Id from the url (like "store.com/product/123456"). Then using such product Id, the product information is retrieved from a graphql API and set in "product" state variable.

The problem occurs when a user enters a url which contains a non-existent product Id; in this case the API does not get any data, so product variable is undefined and the browser displays error "product is undefined".

In theses cases, is it possible to use conditional rendering to display an error message or redirect to a 404 page?

Update:

I'm using functional components.

Upvotes: 0

Views: 123

Answers (2)

Kelvin Yelyen
Kelvin Yelyen

Reputation: 23

To use conditional rendering to display a 404 error message when entered id is false, you could create a 404 page component with a route and test so when id is not recognised, it'll redirect to the 404 page:

  const validId = parseInt(props.match.params.id);
  if (!validId){
    return <Redirect to="/404"/>;
  }

Upvotes: 0

Shaurya Vardhan Singh
Shaurya Vardhan Singh

Reputation: 684

You can use conditional rendering to display either product page or a 404 page

In ComponentDidMount you fetch the data and set it to state and if there is an error you set error to state

During rendering if error is present then display CustomErrPage component else display Productpage component

For example

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      err: null
    }
  }

  componentDidMount() {
    axios.get('store.com/product/123456')
    .then(res => this.setState({
      data: res.data
    }))
    .catch(err => this.state({
      err: err }))
  }

  render() {
    return (
      <div>
        {this.state.err ? <CustomErrPage /> : <ProductPage data={this.state.data} /> }
      </div>
    )
  }
}

Upvotes: 2

Related Questions