Home > Net >  How to set up default value if props is empty? reactJs
How to set up default value if props is empty? reactJs

Time:06-15

I want to use the default value and value from my props for background color. Now I get my value from the field in head of CMS Storyblok. It's a sting. But if I stay it without default value I get my page background color.

import React from "react";
import { Box, Grid } from "@chakra-ui/react";

type SolutionListProps = {
  bgColor: string;
};
const SolutionsList: React.FC<SolutionListProps> = ({  
  bgColor, 
  children, }) => (
  <Box px={5} pt={[10, 20, 120]} pb={[12, 20, 120]} bg={bgColor}> // here I want use it
    <Grid maxW={1170} mx="auto" gap={{ base: 16, md: 32 }}>
      {children}
    </Grid>
  </Box>
);

export default SolutionsList; 

Second file

import React from "react";
import { ReactStoryblokComponent } from "@/types/storyblok";
import { StoryblokComponent } from "storyblok-js-client";
import SolutionsList from "@/components/SolutionsList";
import { renderBody } from "@/sb-utils/renderBody";

const StoryblokSolutionsList: ReactStoryblokComponent<Blok> = ({ blok }) => (
  <SolutionsList bgColor={blok.bgColor}>{renderBody(blok.solutions)}</SolutionsList>
);

type Blok = {
  solutions: StoryblokComponent<string>[];
  bgColor: string;
};

export default StoryblokSolutionsList;

CodePudding user response:

add default value with = "value" in component

import React from "react";
import { Box, Grid } from "@chakra-ui/react";

type SolutionListProps = {
  bgColor: string;
};
const SolutionsList: React.FC<SolutionListProps> = ({  
  bgColor="#000000", 
  children, }) => (
  <Box px={5} pt={[10, 20, 120]} pb={[12, 20, 120]} bg={bgColor}> // here I want use it
    <Grid maxW={1170} mx="auto" gap={{ base: 16, md: 32 }}>
      {children}
    </Grid>
  </Box>
);

export default SolutionsList; 

when parent pass props, it will take value from props, when props is empty, it will take default value which is #000000 in current example

  • Related