Optional and Default Props
Learn about optional and default props in frontend development.
We'll cover the following...
A prop can be optional so that the consumer doesn’t necessarily have to pass it into a component. For example, we could have an optional prop in the Question
component that allows a consumer to change whether the content of the question is rendered or not. We’ll do this now:
We need to add the content to the
Question
component, so add the following code beneath the question title in the JSX:
export const Question = ({ data }: Props) => (<div><div>{data.title}</div><div>{data.content.length > 50? `${data.content.substring(0, 50)}...`: data.content}</div><div>{`Asked by ${data.userName} on${data.created.toLocaleDateString()} ${data.created.toLocaleTimeString()}`}</div></div> );
Here, we have used a JavaScript ternary operator to truncate the content if it is longer than 50
characters.
Note: A JavaScript ternary is a short way of implementing a conditional statement that results in one of two branches of logic being executed. The statement contains three operands separated by a question mark (
?
) and a colon (:
). The first operand is a condition, the second is what is returned if the ...