Enable Disable input with button in reactJS / nextJS - reactjs

I have a condition like this.
I want to enable text input if the button is pressed and can edit the text in it.
the question is how to make the function in react js?
my Code:
function App() {
return (
<div className="App">
<label>URL : </label>
<input
placeholder='http://localhost:3000/123456'
disabled
/>
<button type='submit'>Active</button>
</div>
);
}
export default App;

Use useState hook and onClick event like in this example.
import React, { useState } from "react";
function App() {
const [active, setActive] = useState(false)
return (
<div className="App">
<label>URL : </label>
<input
placeholder='http://localhost:3000/123456'
disabled={!active}
/>
<button
type='submit'
onClick={() => setActive(!active)}
>
Active
</button>
</div>
);
}

Related

Trigger "tick box" message in checkbox field

I am using React, and I would like to find a way to trigger this message (that now triggers only when pressing the type="submit" button, on will, is there any action I can use to trigger this message at any point (for example if a user presses any other button)
<input
id="conditions"
type="checkbox"
name="conditions"
ref={acceptConditions}
required
></input>
This can be achieved with reportValidity() MDN documentation
setTimeout(() =>
document.getElementById('example').reportValidity(),
3000
)
<input id="example" type="checkbox" required />
Ok here are a few approaches, that works.
approach 1
Using the reportValidity()
This function will check the validity of the element and then trigger the event.
import { useRef } from "react";
import "./styles.css";
export default function App() {
const acceptConditions = useRef();
const formRef = useRef();
const handleSubmit = () => {
acceptConditions.current.reportValidity();
};
return (
<form ref={formRef}>
<input
id="conditions"
type="checkbox"
name="conditions"
ref={acceptConditions}
required
></input>
<span>Tick this box to continue</span>
<br />
<button type={"submit"}>submit the form</button>
<br />
<button onClick={handleSubmit}>Imposter button</button>
</form>
);
}
This is a good apporach And one that i recommend.
approach 2:
First of all if you want any other button to trigger the same event then you can do is make a reference to the form and then submit the form manually on the button press.
Here is an example.
import { useRef } from "react";
import "./styles.css";
export default function App() {
const acceptConditions = useRef();
const formRef = useRef();
const handleSubmit = () => {
console.log(formRef.current.submit);
};
return (
<form ref={formRef}>
<input
id="conditions"
type="checkbox"
name="conditions"
ref={acceptConditions}
required
></input>
<span>Tick this box to continue</span>
<br />
<button type={"submit"}>submit the form</button>
<br />
<button onClick={handleSubmit}>Imposter button</button>
</form>
);
}
in the above code the imposter button will trigger the same action as the button with the type="submit".
thank you.

How to open input fields based on radio button selection in React?

I have two radio buttons. Based on which radio button is selected, I need to open input fields to collect some data. How can I achieve this using react?
I tried manipulating the onClick and onChange functions.
Here is the code
import { useState, useEffect } from 'react';
const App = () => {
const [itWorks, setItWorks] = useState(false)
function handleClick(){ SetItWorks(!itworks) }
return (
<div>
{itWorks ?
<>
'It works!'
<input type="text" />
</>: 'It does not'}
<button onClick={() => setItWorks(!itWorks)} >Press me
<input type='radio' aria-selected onClick={handleClick} />
</div>
) }
export default App;

Grabbing the Value of a Dynamically Created Object

I am dynamically creating buttons from an API call that looks like this:
My goal is that when a button is clicked the inner text will display in the search bar above.
below is the code for this auto complete component:
const Autocomplete = (props) =>
{
const btnSearch = (e) => {
console.log(props.suggestions)
}
return(
<>
{props.suggestions.map((e) => (
<button className={style.btn} onClick={btnSearch} key={e}>{e}</button>
))}
</>
);
}
export default Autocomplete;
The Autocomplete component is then being placed in a div as seen here:
return (
<>
<div className={style.container}>
<div className={style.title_hold}>
<h1>turn one</h1>
<h2>a search engine and game companion for Magic: The Gathering</h2>
</div>
<input className={style.search} type='text' placeholder='search for cards here...' value={search} onChange={handleInputChange} onKeyPress={handleSubmit}></input>
<div className={style.btn_wrap}>
<Autocomplete suggestions={results} />
</div>
<div className={style.data_wrap} id='user_display'>
<div className={style.img_wrap}>
{photos}
</div>
<div className={style.display_info}>
<h2>{card.name}</h2>
<h2>{card.type_line}</h2>
<h2>{card.oracle_text}</h2>
</div>
</div>
</div>
</>
)
Any help would be appreciated.
You can create a state variable in your parent component and then pass a function to the Autocomplete's button for the onClick which will then update the state in the parent. Something like this:
const Autocomplete = (props) => {
return(
<>
{props.suggestions.map((e) => (
<button className={style.btn} onClick={() => props.setSearch(e)} key={e}>{e}</button>
))}
</>
);
}
export default Autocomplete;
Your parent component:
import React from 'react'
const ParentComponent = (props) => {
const [searchText, setSearchText] = React.useState("")
const handleClick = (textFromButtonClick) => {
setSearchText(textFromButtonClick)
}
return (
<>
<div className={style.container}>
<div className={style.title_hold}>
<h1>turn one</h1>
<h2>a search engine and game companion for Magic: The Gathering</h2>
</div>
<input className={style.search} type='text' placeholder='search for cards here...' value={searchText} onChange={handleInputChange} onKeyPress={handleSubmit}></input>
<div className={style.btn_wrap}>
<Autocomplete setSearch={handleClick} suggestions={results} />
</div>
<div className={style.data_wrap} id='user_display'>
<div className={style.img_wrap}>
{photos}
</div>
<div className={style.display_info}>
<h2>{card.name}</h2>
<h2>{card.type_line}</h2>
<h2>{card.oracle_text}</h2>
</div>
</div>
</div>
</>
)
}
export default ParentComponent;
I took over your input value in the parent component, but without seeing any of your other code, I have no idea how you're managing that but you can likely merge it into this workflow to wire it up.

How can we make a form url valid for 48 hrs in react hooks

On click on a button how can we create a dynamic form url with below fields using react hooks and url globally valid only for 48 hrs.
https://localhost/aB123GHedFGH138HGxYz/recommendform
import React, { useState, useEffect, useRef } from "react";
import "./styles.css";
export default function App() {
// nominee text field
// description
// nominatedby
// save button
// cancel button
const [createForm, setCreateForm] = useState([
{ nominee: "", description: "", nominatedby: "" }
]);
const inputForm = (choiceForm) => {
alert("Hello");
};
return (
<div className="App">
<h1>Form</h1>
<form>
{createForm.map((field, index) => {
<div key={index}>
<input name="nominee" type="text" />
</div>;
})}
<input value="Create Form" type="button" onClick={inputForm} />
</form>
</div>
);
}
https://codesandbox.io/s/wonderful-wilson-hmts5?file=/src/App.js:0-311
Here is an example of creating a form as you asked.
Adding 48h limit globally (meaning it should persist for all users) requires a server, then you will just need to fetch/update the status. See API and AJAX calls in docs.
const formFields = [
["nominee", "Example"],
["description", "Desc"],
["nominatedby", ""]
];
export default function App() {
const [isFormCreated, setIsFormCreated] = useState(false);
const onClickEnableForm = () => setIsFormCreated(true);
return (
<div className="App">
<h1>Form</h1>
{isFormCreated && (
<form>
{formFields.map(([name, value]) => {
return (
<div key={name}>
<input defaultValue={value} name={name} type="text" />
</div>
);
})}
<input type="submit" />
</form>
)}
{!isFormCreated && (
<input value="Create Form" type="button" onClick={onClickEnableForm} />
)}
</div>
);
}

Select multiple checkboxes without toggling

I am new to react. I am trying to create a component that hides a div when a checkbox is clicked. The problem I am having is, if I introduce more than one checkbox the divs visibility is toggled. Is there an alternative way to allow the selection of all checkboxes?
The functionality should be: click a checkbox or multiple > div remains hidden until all checkboxes are cleared or unchecked.
JSX:
import React, { useState } from 'react';
function reactComponent() {
const [isChecked, setIsChecked] = useState(false);
const toggle = () => setIsChecked(!isChecked);
return (
<div>
<div>
<input type="checkbox" id="option" name="option" onClick={toggle} />
<label for="scales">option</label>
</div>
<div>
<input type="checkbox" id="option" name="option" onClick={toggle} />
<label for="scales">option</label>
</div>
<div className={isChecked ? "hide" : "block "}>
<h3 className="red bold">Content</h3>
<p>lorem Ipsum</p>
</div>
</div>
)
}
export default reactComponent
To achieve what you've described you could use controlled inputs for checkboxes and have a separate piece of state for every checkbox. Here is Codesandbox demo of an example below (you can change some to every in shouldShow flag if you need to show the div if and only if all the checkboxes are checked).
function App() {
const [isChecked, setIsChecked] = useState({ option1: false, option2: false })
const toggle = ({ target: { name } }) =>
setIsChecked({ ...isChecked, [name]: !isChecked[name] })
// Are there any checked ones?
const shouldShow = Object.values(isChecked).some(val => val)
return (
<>
<div>
<input
type="checkbox"
id="option1"
name="option1"
checked={isChecked.option1}
value={isChecked.option1}
onClick={toggle}
/>
<label for="option1">option1</label>
</div>
<div>
<input
type="checkbox"
id="option2"
name="option2"
checked={isChecked.option2}
value={isChecked.option2}
onClick={toggle}
/>
<label for="option2">option2</label>
</div>
<div className={shouldShow ? "hide" : "block "}>
<h3 className="red bold">Content</h3>
<p>lorem Ipsum</p>
</div>
</>
)
}
If you render your checkboxes from an array, you can always check if the length of that array is the same as the length of the checked array kept in state.
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const myOptions = ["option1", "option2", "option3", "option4"];
const [myChecked, setMyChecked] = useState([]);
const toggle = e => {
e.persist();
if (e.target.checked) {
setMyChecked(oldArray => [...oldArray, e.target.name]);
} else {
setMyChecked(oldArray => oldArray.filter(item => item !== e.target.name));
}
};
const showDiv = () => {
return myChecked.length === myOptions.length;
};
return (
<div>
{myOptions.map(option => (
<div>
<label>
<input type="checkbox" name={option} onChange={toggle} />
{option}
</label>
</div>
))}
<div className={showDiv() ? "block" : "hide "}>
<h3>Content</h3>
<p>lorem Ipsum</p>
</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Codesandbox

Resources