You're pretty close, the problem you're facing is that props are an object even when you're passing a single item.
interface TestComponentProps {
str: string;
}
function TestComponent({str}: TestComponentProps) {
return <span>Hello, your string was {str}</span>
}
You then call it with either of the following syntaxes:
<TestComponent str='abcde' />
<TestComponent str={'abcde'} />
str={'abcde'}
just means that React should evaluate 'abcde'
. Since it's a string literal, nothing changes.
However, this has an important caveat, string literals do not have any HTML-escaping applied. So you must do this handling yourself.
The React documentation does a good job at explaining what is happening under the hood here. But in short, JSX is just syntatic sugar and these are the equivalent of writing:
React.createElement(TestComponent, {str: 'abcde'}, null);
From this, you can probably guess what happens if we were to add a second prop.
interface TestComponentProps {
str: string;
coolString: string;
}
function TestComponent({str, coolString}: TestComponentProps) {
return <span>Hello, your string was {str} and your coolString was {coolString}</span>
}
<TestComponent str="abcde" coolString={'fghi'}/>
So, what's the third parameter? That's for children. Typing for children was stolen from this answer. Let's see it in action.
interface TestComponentProps {
str: string;
children: React.ReactNode
}
function TestComponent({str, children}: TestComponentProps) {
return (<>
<span>Hello, your string was {str}</span>
<div>
{children}
</div>
</>);
}
<TestComponent str={'<3'}>
<p>Hey there! 1 + 1 = {1 + 1}</p>
<p>I'm another child!</p>
</TestComponent>
Becomes:
function TestComponent({
str,
children
}) {
return React.createElement(React.Fragment, null, React.createElement("span", null, "Hello, your string was ", str), React.createElement("div", null, children));
}
React.createElement(TestComponent, {
str: '<3'
}, React.createElement("p", null, "Hey there! 1 + 1 = ", 1 + 1), React.createElement("p", null, "I'm another child!"));
Note: The <>
</>
syntax is called a Fragment and is essentially a grouping function that has no DOM output.