React: 条件付きでコンポーネントにインラインプロップを渡す方法
React: コンポーネントに条件付きでインラインプロップを渡す
Reactコンポーネントに条件付きでインラインプロップを渡す方法はいくつかありますが、ここでは最も一般的な方法であるインライン条件式とオブジェクトリテラルについて解説します。
インライン条件式を使用すると、コンポーネントに渡すプロップを条件によって動的に決定できます。
const MyComponent = ({ condition, propValue }) => {
return (
<div>
{condition && <p>{propValue}</p>}
</div>
);
};
上記の例では、condition
が true
の場合のみ、propValue
を持つ <p>
タグがレンダリングされます。
オブジェクトリテラルを使用すると、コンポーネントに渡すプロップをより詳細に制御できます。
const MyComponent = ({ condition, propValue }) => {
const props = {};
if (condition) {
props.propValue = propValue;
}
return (
<div>
<p {...props} />
</div>
);
};
例
以下の例では、MyButton
コンポーネントに disabled
プロップを条件付きで渡します。
const MyButton = ({ label, disabled }) => {
return (
<button disabled={disabled}>
{label}
</button>
);
};
const App = () => {
const [isButtonDisabled, setIsButtonDisabled] = useState(false);
return (
<div>
<MyButton label="Button 1" disabled={isButtonDisabled} />
<button onClick={() => setIsButtonDisabled(!isButtonDisabled)}>
Toggle Button 1 Disabled
</button>
</div>
);
};
この例では、isButtonDisabled
ステートが true
の場合、MyButton
コンポーネントは disabled
プロップが true
でレンダリングされます。
Reactコンポーネントに条件付きでインラインプロップを渡す方法はいくつかありますが、インライン条件式とオブジェクトリテラルが最も一般的です。それぞれの方法には長所と短所があるので、状況に応じて適切な方法を選択してください。
サンプルコード: React: コンポーネントに条件付きでインラインプロップを渡す
import React from 'react';
const MyComponent = ({ condition, propValue }) => {
return (
<div>
{condition && <p>{propValue}</p>}
</div>
);
};
const App = () => {
const [showPropValue, setShowPropValue] = React.useState(false);
return (
<div>
<MyComponent condition={showPropValue} propValue="Hello, World!" />
<button onClick={() => setShowPropValue(!showPropValue)}>Toggle Prop Value</button>
</div>
);
};
export default App;
説明:
MyComponent
コンポーネントは、condition
プロップとpropValue
プロップを受け取ります。App
コンポーネントは、showPropValue
ステートを保持します。MyComponent
コンポーネントにshowPropValue
ステートと"Hello, World!"
を渡します。- ボタンをクリックすると、
showPropValue
ステートが反転し、MyComponent
コンポーネントに渡されるcondition
プロップが更新されます。
オブジェクトリテラル
import React from 'react';
const MyComponent = ({ condition, propValue }) => {
const props = {};
if (condition) {
props.propValue = propValue;
}
return (
<div>
<p {...props} />
</div>
);
};
const App = () => {
const [showPropValue, setShowPropValue] = React.useState(false);
return (
<div>
<MyComponent condition={showPropValue} propValue="Hello, World!" />
<button onClick={() => setShowPropValue(!showPropValue)}>Toggle Prop Value</button>
</div>
);
};
export default App;
condition
がshowPropValue
ステートと等しいオブジェクトを作成し、MyComponent
コンポーネントに渡します。
補足:
- 上記のサンプルコードは、React Hooks を使用しています。React Hooks を使用していない場合は、クラスベースコンポーネントで同様のロジックを実装できます。
- コンポーネントに渡すプロップは、コンポーネントの定義に従って変更する必要があります。
- 条件付きでコンポーネント自体をレンダリングする場合は、
React.createElement
またはconditional rendering
を使用できます。
React: コンポーネントに条件付きでインラインプロップを渡す: 他の方法
Reactコンポーネントに条件付きでインラインプロップを渡す方法は、上記で紹介したインライン条件式とオブジェクトリテラル以外にもいくつかあります。ここでは、いくつか例を挙げます。
テ Ternary Operator
const MyComponent = ({ condition, propValue }) => {
return (
<div>
{condition ? <p>{propValue}</p> : null}
</div>
);
};
&& 演算子
const MyComponent = ({ condition, propValue }) => {
return (
<div>
{condition && <p>{propValue}</p>}
</div>
);
};
フショートサーキット評価
const MyComponent = ({ condition, propValue }) => {
return (
<div>
<p>{condition && propValue}</p>
</div>
);
};
カスタムフック
import React, { useState } from 'react';
const useConditionalProp = (condition, propValue) => {
const [props, setProps] = useState({});
React.useEffect(() => {
if (condition) {
setProps({ propValue });
} else {
setProps({});
}
}, [condition, propValue]);
return props;
};
const MyComponent = ({ condition, propValue }) => {
const props = useConditionalProp(condition, propValue);
return (
<div>
<p {...props} />
</div>
);
};
Render props
const MyComponent = ({ render }) => {
return render();
};
const ConditionalProp = ({ condition, propValue }) => {
if (condition) {
return <p>{propValue}</p>;
} else {
return null;
}
};
const App = () => {
return (
<div>
<MyComponent render={() => <ConditionalProp condition={true} propValue="Hello, World!" />} />
</div>
);
};
Higher-order components (HOC)
const withConditionalProp = (condition) => (WrappedComponent) => {
return (props) => {
if (condition(props)) {
return <WrappedComponent {...props} />;
} else {
return null;
}
};
};
const MyButton = ({ label, disabled }) => {
return (
<button disabled={disabled}>
{label}
</button>
);
};
const ConditionalButton = withConditionalProp((props) => !props.disabled)(MyButton);
const App = () => {
return (
<div>
<ConditionalButton label="Button 1" disabled={false} />
<ConditionalButton label="Button 2" disabled={true} />
</div>
);
};
context
import React, { useContext } from 'react';
const MyContext = React.createContext({ condition: false, propValue: '' });
const MyComponent = () => {
const { condition, propValue } = useContext(MyContext);
return (
<div>
{condition && <p>{propValue}</p>}
</div>
);
};
const App = () => {
const [condition, setCondition] = useState(false);
const [propValue, setPropValue] = useState('Hello, World!');
return (
<MyContext.Provider value={{ condition, propValue }}>
<div>
<MyComponent />
<button onClick={() => setCondition(!condition)}>Toggle Condition</button>
<button onClick={() => setPropValue('Goodbye, World!')}>Change Prop Value</button>
</div>
</MyContext.Provider>
);
};
それぞれの方法の長所と短所
- インライン条件式: シンプルでわかりやすいですが、条件が複雑になると読みづらくなる可能性があります。
- オブジェクトリテラル: より多くの制御が可能ですが、コードが冗長になる可能性があります。
- Ternary Operator: 短く書き換えられますが、複雑な条件には適
javascript reactjs inline