jsx
function MyComponent(props) {
return <div>{props.displayString}</div>;
}
function MyComponent(props) {
return <div>{props.displayString}</div>;
}
function ConditionalComponent({ condition }) {
return (
<>
{condition ? (
<p>Condition is true</p>
) : (
<p>Condition is false</p>
)}
</>
);
}
// Usage
<ConditionalComponent condition={true} />;
function Parent({ data }) {
return <IntermediateComponent data={data} />;
}
function IntermediateComponent({ data }) {
return <ChildComponent data={data} />;
}
function ChildComponent({ data }) {
return <p>Received data: {data}</p>;
}
// Usage
<Parent data="Some data" />;
import { useState } from "react";
function ClickableComponent() {
const [clicked, setClicked] = useState(false);
return (
<button onClick={() => setClicked(true)}>
{clicked ? "Button clicked" : "Click me"}
</button>
);
}
function TextInputComponent() {
const [text, setText] = useState("");
return (
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Enter text"
/>
);
}
React doesn't have a built-in preview feature. However, you can use a tool like Storybook to create previews for your components in a separate development environment.
function ListComponent({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}
// Usage
const items = ["Item 1", "Item 2", "Item 3"];
<ListComponent items={items} />;
function ItemKeysExample({ items }) {
return (
<ul>
{items.map((person) => (
<li key={person.id}>
Name: {person.name}, Age: {person.age}
</li>
))}
</ul>
);
}
// Usage
<ItemKeysExample
items={[
{ name: "John", age: 30, id: "1" },
{ name: "Jane", age: 28, id: "2" },
{ name: "Bob", age: 25, id: "3" },
]}
/>;
function Parent({ header, content }) {
return (
<div>
{header}
{content}
</div>
);
}
// Usage
<Parent header={<h1>Header</h1>} content={<Child />} />;
function Child() {
return <p>Child Content</p>;
}
React doesn't have a direct analog to modifiers in Jetpack Compose or SwiftUI. Instead, you can use inline styles or CSS classes.
function ModifiersExample() {
const style = {
padding: "16px",
backgroundColor: "blue",
color: "white",
};
return <div style={style}>Hello, World!</div>;
}
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
import { createContext, useContext } from "react";
const CustomContext = createContext();
function Parent({ data }) {
return (
<CustomContext.Provider value={data}>
<Intermediate />
</CustomContext.Provider>
);
}
function Intermediate() {
return <Child />;
}
function Child() {
const data = useContext(CustomContext);
return <p>Received data: {data}</p>;
}
// Usage
<Parent data="Some data" />;
import { useEffect } from "react";
function SideEffectOnLoadComponent() {
useEffect(() => {
// Perform side effect, e.g. fetch data, update external data source
}, []);
// Other UI components
return <div />;
}