Conditional statements to show a different component React js - javascript

i want to create a function or a conditional statement you can say that can show different components based on "If the user have bought products" then show the products components otherwise show "just a simple text like browse or buy products."
<div>
<Bookscard />
</div>
so this is my component, inside the component the purchased products are being mapped. Can i get a conditional statement that can either show this component like ( if user.courses is greater than or equal to 1 then show the component otherwise show a text ) something like this

You can try this:
<div>
{ user.courses.length > 0 &&
<Bookscard />
}
{ user.courses.length > 0 ||
<NoResults />
}
</div>
Or you can keep consistency with && by:
<div>
{ user.courses.length > 0 &&
<Bookscard />
}
{ user.courses.length == 0 &&
<NoResults />
}
</div>

Adding up to #Antoine Baqain's answer, you could use ternary operator too, like this:
<div>
{ user?.courses?.length > 0 ? <Bookscard /> : <NoResults /> }
</div>

Related

How to set condition value in Reactjs

I try to set a condition
initialValue = {
this.props.noteviewReducer.isError &&
this.props.noteviewReducer.result.body
}
if (this.props.noteviewReducer.isError) true then show this.props.noteviewReducer.result.body
if not, then not show
Try something like this
<div>
{this.props.noteviewReducer.isError && (
<MyComponent initialValue={this.props.noteviewReducer.result.body} />
)}
</div>

React Typescript - Show hidden Divs not currently showing

I have an array that contains Title1, Title2, Title3, all the way to Title8. If that item is not empty I want to display with it's corresponding information. Currently that works.
However I want to add a button that will allow me to display all fields. For example let's say Title1 through Title3 is not null. It will show that (which it currently does). I want to add a button that when clicked will display all Titles 1-8.
Here is my current code. In the code below I'm only showing 4 if statements and removed all content to save space:
{ this.state.showExtraRows? <div>
{ this.state.Product[0].Title1 ?
<div>
//Display some fields here
</div>
: null
}
{ this.state.Product[0].Title2 ?
<div>
//Display some fields here
</div>
: null
}
{ this.state.Product[0].Title3 ?
<div>
//Display some fields here
</div>
: null
}
{ this.state.Product[0].Title4 ?
<div>
//Display some fields here
</div>
: null
}
</div>
: null
}
<button className={styles.btn}
type="button"
onClick={()=>{this.setState({showExtraRows:!this.state.showExtraRows})}}>
{ this.state.showExtraRows? 'Hide Rows' : 'Show Rows'}
</button>
I'm not too sure if I'm supposed to wrap the whole thing in the this.state.showExtraRows? statement.
I think it's better to use a map function here
const productWithTitles = this.state.Product.filter((Product) => !!Product.title);
return (
<div>
{this.state.showExtraRows && (
<div>
{productWithTitles.slice(0, 3).map((product) => {
return (
<div>
//Display some fields here
</div>
);
})}
</div>
)}
</div>
);

How do I make it mandatory to select at least two options using the React Multiselect component?

I created one form control using the React Multiselect component. In this control, I want the 'required' to be removed when at least two of the Multiselect fields are selected.Required does not appear when user selects even one. Required appears only when nothing is selected. How can I do that?
React JS
const changeSelected = (selectedList, selectedItem) => {
const values = selectedList.toString();
setInput({...input, value: values})
dispatch(saveAnswer('f3', formKey, values))
}
return (
<>
<p>{comboboxName}</p>
<Multiselect className='btn-group'
style={{background: "red"}}
isObject={false}
closeIcon="close"
options={options} // Options to display in the dropdown
selectedValues={input.value ? input.value.split(',') : []} // Preselected value to persist in dropdown
onSelect={changeSelected} // Function will trigger on select event
onRemove={changeSelected} // Function will trigger on remove event
placeholder=''
/>
<p></p>
<Form.Check>
<Form.Check.Input required
checked={input.value != null && input.value.length > 1}
style={{display:'none' }}
/>
<Form.Control.Feedback type="invalid" >Required</Form.Control.Feedback>
</Form.Check>
</>
)
I guess this would solve your problem:
<Form.Check.Input
required = {input.value.length < 2 ? true : false}
checked={input.value != null && input.value.length > 1}
style={{display:'none' }}
/>

Show character limit under input in React Js

I am creating a react input component and need to show the character limit underneath the input ex: (0/500 characters remaining). I have passed the maxLength as a prop into the input component but am unsure of how to show the number of characters remaining before the limit is reached.
The max length works properly - how can I add the visual feedback of showing how many characters are remaining (2/500 characters... etc).
<input
{...customAttributes}
maxLength={maxLength}
required={required}
/>
And then I call my component like so:
<InputComponent maxLength={10} />
The question does not have enough information to answer correctly, but based on the reaction to the comment, something like this should work:
<div>
{this.props.maxLength - this.state.whateverYouNamedTheValue.length}/{this.props.maxLength}
</div>
In the context of a component, cleaned up with ES6 a bit:
class InputComponent extends React.Component {
// ... class and state stuff ...
render() {
const { maxLength } = this.props;
const { whateverYouNamedTheValue } = this.state;
return (
<div>
<input
{...customAttributes}
maxLength={maxLength}
required={required}
/>
{ whateverYouNamedTheValue ? (
<div>
({ maxLength - whateverYouNamedTheValue.length }/{ maxLength })
</div>
) : null }
</div>
);
}
}

Passing JSX to components vs dangerouslySetInnerHTML

I've been working through react examples, and I've been hacking away building some components. Now I feel i'm running into a fundamental "Brain Fart", regarding component structure and nesting.
What I'm after:
Input component with Optional Labels and help text.
What I have right now: ( which does work )
Input.js
//...//
var MyInput = React.createClass( {
render: function() {
//...//
var helpText = null;
if( typeof this.props.helpText !== 'undefined' ){
helpText = <p className="help-block" > {this.props.helpText} </p>;
}
return (
<div className={ className }>
<MyLabel showLabel={ this.props.showLabel} htmlFor={ this.props.name }>
{ this.props.title }
</MyLabel>
<input
type={ this.props.type || 'text' }
name={ this.props.name }
onChange={ this.changeValue }
value={ this.getValue() }
checked={ this.props.type === 'checkbox' && this.getValue() ? 'checked' : null }
placeholder={ this.props.title }
/>
<span className='validation-error'>{ errorMessage }</span>
{helpText}
</div>
);
}
});
module.exports = MyInput;
LoginForm.js
//...//
var LoginForm = React.createClass({
// ... //
render: function() {
return (
<Form className=" col-sm-11 col-lg-10 block-center loginFrm" >
<div className="row">
<FrmInput value =""
name="username"
title="Username"
className="col-sm-5"
showLabel={false}
helpText= { <span> Help text with link </span>}
required />
<FrmInput value =""
type="password"
name="password"
title="Password"
className="col-sm-5"
showLabel={false}
required />
<button type="submit"
className="btn btn-default input-sm "
>
Sign In
</button>
</div>
<div className="row">
<div className="pull-right" >
<FrmCheckbox name="rememberMe"
title="Remember Me"
/>
</div>
</div>
</Form>
);
},
});
module.exports = LoginForm;
Making the label optional was easy. I use a BOOL showLabel property on the <MyInput/> component and pass that into the MyLabel component. showLabel is assumed TRUE, so the label is shown unless you set showLabel to false as seen above ( then <MyLabel/> just returns NULL ).
I first tried a similar method with a <help/> component to add the optional help text after the input inside <MyInput/>. Everything worked until I added a link inside the help text. Researching I found dangerouslySetInnerHTML as a means to pass HTML content into a component. While testing I also found the code above appears to work also, though I'm not exactly sold on why and how "good" this approach is.
In short it appears I'm just passing JSX objects into my component for rendering. inside <Form> (from LoginForm.js ) on the <FrmInput/> component there is a property named helpText set as follows
helpText= { <span> Help text with link </span> }
inside the <MyInput/> component I'm testing/listening for the helpText property and setting it to a variable when found (Again wrapping with JSX)
var helpText = null;
if( typeof this.props.helpText !== 'undefined' ){
helpText = <p className="help-block" > {this.props.helpText} </p>;
}
Then in the Render Method I have { helpText }
All in all it looks like I'm just passing javascript objects ( via JSX ) on through untill the final render method. I have not seen the above used in tutorials or documentation, so I'm just looking for a professional opinion.
Is the above "good" practice or how could this better be handled.
There's nothing 'wrong' with your approach. A few suggestions that can help stream line a bit.
You can shorten this block to a simple inline ternary:
var helpText = null;
if( typeof this.props.helpText !== 'undefined' ){
helpText = <p className="help-block" > {this.props.helpText} </p>;
}
You can remove the above and in your render replace {helpText} with:
{ this.props.helpText ? this.props.helpText : null }
In form input remove the inline helpText html and move to a variable using parens for the JSX.
const helpTextContent = ( <span> Help text with link </span> );
Then inline: helpText = { helpTextContent }
Lastly if you're using ES6 you can use the following syntax to make using props less cumbersome:
let { helpText, someOtherProp, anotherProp } = this.props;
Then you can just refer to helpText or someOtherProp directly without the this.prop every time.
Hope that helps!

Categories

Resources