set first box clicked as a default at the first load - reactjs

Im new in reactjs and I create a list of card by mapping in reactjs but I want my first card be clicked as a default at the first load what can i do for this code.
<div className="d-flex">
{data && data.length > 0
? data.map((item, index) => {
return (
<>
<div className="box-stock" onClick={() => selectData(item)}>
<div className="top-stock skewed p-5">
<h1>{item.symbol}</h1>
<strong className="text-center">
<span> (0.25)</span>
{item.stockNum}
</strong>
<Label className="text-center">
EPS:<span className="text-white">{item.EPS}</span>
</Label>
<Label className="text-center">
P/E:<span className="text-white">{item.PE}</span>
</Label>
</div>
</div>
</>
);
})
: 'no data'}
</div>

You can use useEffect hook to run program once it renders. Here, in useEffect pass empty array as a dependency so, that it runs only once.
useEffect(() => {
selectData(data[0])
}, [])

You can add click event on first load using javascript. The button will trigger the event on first load and you will get your first card clicked. Here is the code:
document.getElementsByClassName("box-stock").click()

Related

How to disable second form if first one is clicked

I have two fields that show a modal when clicked on. I want to make one disabled if I select anyone first. I am using react-bootstrap for this project
<>
<div className='add-edit-product'>
<div className='d-flex align-items-center justify-content-center error-info mb-3'>
<img src={`../../../assets/img/about/${data.currencyHedge && data.marginFinancing ? "error-info-success.png" : "error-info.png"}`} className='me-3' />
{data.currencyHedge && data.marginFinancing ?
<p className='success'>Risks are acceptable due to mitigants</p> :
<p className='error'>The below risks require your attention</p>
}
</div>
<div className='form'>
<h2 className='mb-3'>Exchange rate risk</h2>
{data.currencyHedge && data.marginFinancing ? <p>No risk</p> :
<div>
{/*clicking on either of this tab will show a modal*/}
<div className='risk-tab' onClick={() => { setcurrencyHedgeModal(true); setSelected("currencyHedge") }}>
<h3>Enter a currency hedge</h3>
<img src={`../../../assets/img/about/${data.currencyHedge ? "correct-success.png" : "correct (1).png"}`} />
</div>
<div className='risk-tab' onClick={() => {setfinancingSufficientlyModal(true); setSelected("marginFinancing")}}>
<h3>Margin the financing sufficiently</h3>
<img src={`../../../assets/img/about/${data.marginFinancing ? "correct-success.png" : "correct (1).png"}`} />
</div>
</div>
}
</div>
</div>
<div className='footer_'>
<button onClick={() => hendelCancel()} className="footer_cancel_btn">cancel</button>
<button onClick={() => { nextStep() }} className='footer_next_btn'> Next</button>
</div>
{currencyHedgeModal && <CurrencyHedgeModal show={currencyHedgeModal} onHide={() => setcurrencyHedgeModal(false)} getModalData={(e) => modalGetData(e)} type={selected} />}
{financingSufficientlyModal && <FinancingSufficientlyModal show={financingSufficientlyModal} onHide={() => setfinancingSufficientlyModal(false)} getModalData={(e) => setData({ ...data, marginFinancing: e })} />}
</>
how can I add the logic to disable the next field if anyone is selected first. the image below is the form. (the green check mark shows when each form is filled and saved)
Question answer 1
Yes, if you want both inputs to trigger the opening of the modals you have to set onClick prop on both.
This depends on implementation and what do you specifically mean by disable an input. There are a couple of possible scenarios:
2.1 You may add a disabled class like so:
className={`${isOpened ? "disabled" : ""}`}
and then write some css.
2.2 You might rewrite onClick to just return when the modal is already opened instead of opening the second modal like so:
onClick={() => {
if (isOpened) return
setOpened(true)
}
P.S. You may need to add a second boolean flag to your state if you want this behaviour on both modals / inputs
Original answer
You have to use useState hook with a boolean flag isOpened
const [isOpened, setOpened] = useState(false)
Then update the state when clicking on yout input field
onClick={() => setOpened(true)}
Finally in your input fields you can use isOpened to disable them however you want, using styles or other logic.
P.S. Don't forget to call setOpened(false) when closig your modal

Display a specific component by its key

I have this WP API data that I'm fetching in to a component called "HostingCard". I am mapping through this component which renders three cards. While mapping through these I am assigning a key to each of them.
`{hostings.map((hosting) => (
<HostingCard key={hosting.id} hosting={hosting} setHosting={setHostings} />
))}`
Each card has one of these titles "Pro", "Standard" and "Basic".
I made it so that once a card is clicked a new component appears. This component is called "ContactFormular".
Now in the "ContactFormular" component I want to display the information that was on the card that was clicked. is this possible?
Here's the code that opens a new component once the card/button is clicked:
import ContactFormular from './ContactFormular'
const HostingCard = ({post, handleSubmit, hosting, setHosting, showContactDialog, setShowContactDialog, ssl, setPro, pro, key}) => {
return (
<div className='noselect hosting-options'>
<input type="radio" id={post.acf.hosting} name="startup" />
<div className='card selected-card'>
<form onSubmit={handleSubmit}>
<label for={post.acf.tilvalg} className='label'>
<div className='card-header'>
<h5>{hosting.acf.title}</h5>
<p>{hosting.acf.beskrivelse}</p>
</div>
<div className='pakke-detaljer'>
<div>
<p style={{display: hosting.acf.deltaljer ? 'block' : 'none'}}>{hosting.acf.deltaljer}</p>
</div>
</div>
<div className='button-header' onClick={() => setPro(false)}>
<button className='btn' onClick={() => setShowContactDialog(true)}>Vælg</button>
</div>
</label>
</form>
</div>
<ContactFormular key={hosting.id} post={post} hosting={hosting} setHosting={setHosting} showContact={showContactDialog} setShowContact={setShowContactDialog} handleSubmit={handleSubmit} ssl={ssl} pro={pro} setPro={setPro}/>
</div>
)
}
It looks like you're passing in showContactDialog as a parameter and using that to decide whether or not to show this new component right? That means you need showContactDialog to be true for only the one you clicked on, and false for the others. ie each component needs a different state variable. It looks like you might be sharing the same state variable between all components. It's impossible to tell unless you share a reproducible example

React toggle button based on API return

I am currently working on a React application.
As you can see in the following code, there are two buttons. I would like to show the grey button if the user hasn't created a Request (default). If the user has created a Request the button should be green.
Problem:
The main issue is, that the map function (API) no returning any value for "no Requests" so I am not able to identify "no Requests". That means that .isEmpty,.length, .indexOf,... and also the "if-else" is not working because there is nothing to validate.
const greenButton = (
<Button color="green" onClick={e => DeleteRequest(e, rest.id)}>Request</Button>
);
const greyButton = (
<Button color="grey" onClick={e => CreateRequest(e, props.reservationID)}>Request</Button>
);
return (
<div>
{greyButton}
{requests.map((rest, i) => (
<div key={i}>
{rest.requester === username
? <div>{greenButton}{rest.requester} <i
aria-hidden="true"
className="delete icon"
onClick={e => DeleteRequest(e, rest.id)} />
</div> : <div />}
</div>
))}
</div>
);
Result in the UI:
API:
Any Ideas? (If you need more information, I am happy to provide more details)
conditional rendering
Use a ternary on requests being a defined/truthy object and has a truthy length property. In the true branch map the requests, grey button in false branch. This covers requests being either initially (or returned from the API) undefined or an empty array [].
return (
<div>
{requests && requests.length ? requests.map((rest, i) => (
<div key={i}>
{rest.requester === username
? <div>{greenButton}{rest.requester} <i
aria-hidden="true"
className="delete icon"
onClick={e => DeleteRequest(e, rest.id)} />
</div> : <div />}
</div>
)) : (
{greyButton}
)}
</div>
);

How to use simulate(click) function in react unit test

I am beginner level in React test.
I have a component like a small carousel. I want to test if change state(currentPage) when i click. But i didn't. It throws that error message:
Method “simulate” is only meant to be run on a single node. 0 found
instead.
I didnt understand " what is node,which node ? "
That is my test code :
it("check if next button works properly", () => {
const wrapper = shallow(<QuickStartGuide />);
const nextButton = wrapper.find(".quick-start-guide-messages-control-button .next-button");
nextButton.simulate('click');
expect(wrapper.state().currentIndex).toEqual(1);
})
And component :
<div className={containerClassName}>
{isOpen &&
<div className={"quick-start-guide-content-wrapper"}>
<div className="quick-start-guide-header">
<MtButton text={"MINIMIZE"}
hasIcon={true}
onClick={this.handleTriggerButtonClick}
className={"quick-start-guide-minimize-button"}/>
<div className={"quick-start-guide-title"}>{"Quick Start Guide"}</div>
{!!guideMessages.length &&
<Fragment>
<div className={"quick-start-guide-messages"}>
<MtButton className={"quick-start-guide-messages-control-button prev-button"}
hasIcon={true}
onClick={this.handleGoToPrevMessageButtonClick}
isDisabled={!currentGuideMessageIndex}
text={"PREV"}/>
{guideMessages[currentGuideMessageIndex][0]}
<MtButton className={"quick-start-guide-messages-control-button next-button"}
hasIcon={true}
onClick={this.handleGoToNextMessageButtonClick}
isDisabled={currentGuideMessageIndex >= guideMessages.length - 1}
text={"NEXT"}/>
</div>
<div className={"quick-start-guide-indicators"}>
{guideMessages.map((item, index) => (
<IndicatorItem key={item[0].key}
order={index}
onClick={this.handleIndicatorItemClick}
className={classNames({
active: index === currentGuideMessageIndex
})}/>
))}
</div>
</Fragment>}
</div>
<div className={"quick-start-guide-content"}>
<div className={"quick-start-guide-action-buttons"}>
{guideActions.map(([text, handleActionButtonClick, isDisabled = false]) => (
<MtButton key={text}
text={text}
isDisabled={isDisabled}
visualType={BUTTON_VISUAL_TYPES.ROUNDED}
className={"quick-start-guide-action-button"}
onClick={handleActionButtonClick}/>
))}
</div>
</div>
</div>}
<MtButton className={"uick-start-guide-trigger-button"}
text={"GUIDE"}
onClick={this.handleTriggerButtonClick}
hasIcon={true}/>
</div>
The error you're receiving isn't related to the simulate(click) and is an issue with your selector because it's not finding anything to actually click.
Double check that this is the correct selector to use: wrapper.find(".quick-start-guide-messages-control-button .next-button");.
You can use console.log(wrapper.debug()) to check to see what elements are available to select.

Get the button value from semantic ui react

I am a newbie to React.Currently I am facing this problem.
Here is my code
handleClick(e) {
console.log('Click happened'+" "+ e.target.value);//getting UNDEFINED here
}
In the below code locationArr contains many locations
{ locationArr.map((location) => {
console.log(location); //It prints all the locations here NO PROBLEM
if (location !== ' ') {
return (
<div className ="ui stackable four column grid">
<div className="column centered">
</div>
<div className="column">
</div>
<div className="column centered">
<Button size='huge' primary value='{location}' as={Link}
to="/location" onClick={this.handleClick.bind(this)} >
{location} // ABLE TO GET LOCATION NAMES here
</Button>
Now my problem is I want to access the value of the location from the button in handleClick function and I also need to pass it to another component.Anyone please suggest me how do I achieve this?
Change
onClick={this.handleClick.bind(this)} to
onClick={this.handleClick.bind(location)}
Working Demo
Demo solves your both problems.

Resources