1

I am new to React and I have a simple child-component. I want to set default props so if no prop is given when the component is called it uses whatever the defaults are set at. So far I have:

import React from 'react';

interface titleComponentProps {
  title?: string;
}

const titleComponentDefaults = ({
  title: "default title",
})

const titleComponent = ({
  title,
}: titleComponentProps) => {
  return <React.Fragment>{title}</React.Fragment>;
};

export default DynamicHelperText;

I am unclear as to how to have the default props appear in the component. Would anyone know the best way to do this?

1 Answer 1

5

You should be able to pass a default value as you would any argument in a function.

const TitleComponent = ({
  title = 'Default Title',
}: TitleComponentProps) => {
  return <React.Fragment>{title}</React.Fragment>;
};

Your Prop type is correct as title?: string since the ? indicates that you can omit that parameter when calling the component.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.