How to link a text field with a radio button - reactjs

Before Clicking anything text field should be disable . when after the radio button selected my text field must be enable.

This is the working solution of your question.
class App extends React.Component {
state = {
isRadioSelected: true
};
changeHandler = () => {
this.setState({ isRadioSelected: false });
};
render() {
return (
<div className="App">
<h3>Input text is {this.state.isRadioSelected ? 'Disabled': 'Enabled'}</h3>
<input type="text" disabled={this.state.isRadioSelected} />
<br />
<label>Select Radio Button</label>
<input type="radio" onChange={this.changeHandler} />
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root' />

Your description is pretty vague and you don't have any code samples, but here's likely what you want to do:
Make the radio button a controlled component, so that you can access it's value within React's state.
Tie the input's disabled attribute to the value of that state field.
It also seems like you want a checkbox, and not a radio button, since a radio button cannot be untoggled if there is only a single radio button.
This code will likely not work as-is (I haven't run it), but should provide a starting idea:
function Tester() {
const [radioValue, setRadioValue] = useState(false)
return (
<div>
<input type="radio" onClick={(e) => setRadioValue(e.target.value)} value={radioValue} />
<input type="text" placeholder="your input box" disabled={!radioValue} />
</div>
)
}

Related

Pass component input value to the same component in a different class

I have a SearchBarComponent that looks like this
const SearchBarComponent = ({inputStyle, searchIconSize, onChange, formClass, query, name, onClick, formContainerClass}) => {
return (
<div className={formContainerClass}>
<form className={formClass}>
<div class="form-group">
<input type="text" value={query} onChange={onChange} name={name} class="form-control shadow-none" placeholder="Search your dream car.." style={inputStyle}/>
<Link to="/car-list">
<BiSearchAlt2 onClick={onClick} className="search-icon" size={searchIconSize}/>
</Link>
</div>
</form>
</div>
)
};
export default SearchBarComponent;
I have a landing screen with the SearchBarComponent where a user can enter a search query, when they click it, it should populate the SearchBarComponent in the results page (Which is in a different component) so that it moves the props to the other SearchBarComponent and displays the results.
I don't know if it makes sense but here's a small snippet of what I'm looking for but struggling to implement.
https://codesandbox.io/s/epic-bhabha-p5htt4?file=/src/App.js

React Binding syntax

I am making a simple doodle/drawing app for my own tutorial. As a simple first step, I wanted to provide a way for them select the pen color by entering something like Red, Green, or #880000 (hex code).
This is how I implemented it, is there a simpler/neater way?
NOTE: The state variable is defined in the constructor and includes penColor and a few other properties.
<div className='penControls'>
<div>Pen Color
<div className='colorPicker' >
<input type="text" id="penColor" name='penColor' defaultValue={this.state.penColor}
onChange={
(ev) => {
this.state.penColor = document.getElementById('penColor').value;
this.setState(this.state);
}
}
className="penColorPicker mx-4" />
</div>
</div>
</div>
If you're working with React you should avoid the use document API, so there's no need of document.getElementById, use event.target.value that is sent in the event object when calling onChange
Also, never assign a value to your state directly like this
this.state.foo = 'bar';
Use setStatefunction for this:
this.setState({ foo: 'bar' })
That'll dispatch all the component life cycle related to re-rendering in a safe way
Finally, try with the following code...
<div className='penControls'>
<div>Pen Color
<div className='colorPicker' >
<input type="text" id="penColor" name='penColor' defaultValue={this.state.penColor}
onChange={
(ev) => {
const newPenColor = event.target.value;
this.setState({ penColor: newPenColor });
}
}
className="penColorPicker mx-4" />
</div>
</div>
</div>
ReactJS tries to solve the exact problem you are facing of reading from DOM and updating the state. But we need to update the state in React way.
<div className='penControls'>
<div>Pen Color
<div className='colorPicker' >
<input type="text" id="penColor" name='penColor' defaultValue={this.state.penColor}
onChange={
(ev) => {
let newPenColor = this.state.penColor
this.setState({ penColor: newPenColor });
}
}
className="penColorPicker mx-4" />
</div>
</div>
React State Update

How to allow user formatting in React app?

I have a React app where a user can type something into textbox, click 'submit' and then the text appears somewhere.
I want to add functionality which will allow the user to format the text. Just like you can do here on SE when asking questions. For example I want the below input to be shown as bold.
<b>bold</b>
How can I achieve this? Or where to look for this kind of thing?
If you want to enable the same functionality you get in stack overflow, then I think the one way to achieve this would be allowing the user to input markdown and converting that to HTML. This is a library that could help with that: marked
Freecodecamp has a markdown previewer as one of their projects, so if you want to check out some examples, you could probably find hundreds of different implementations: https://www.freecodecamp.org/forum/t/build-a-markdown-previewer/198715
Yes, this can be done using state, as well as a checkbox toggle to determine whether or not the text should be bold or not.
handleChange will update the input. handleFormatChange will update whether or not you should use bold text or not. In the render, a conditional can be implemented to determine when to render what format.
class Formatter extends React.Component {
state = {
format: false,
input: ""
}
handleChange = () => {
this.setState({
input: event.target.value
})
}
handleFormatChange = () => {
this.setState({
format: !this.state.format
})
}
render() {
var input = this.state.format
? <b> {this.state.input} </b>
: <p> {this.state.input} </p>
return (
<div>
Bold <input type="checkbox"
onChange = {
this.handleFormatChange
}
/>
<br />
<input value={this.state.input}
onChange = {this.handleChange}
/>
<br/>
{input}
</div>
);
}
}
ReactDOM.render( <
Formatter / > ,
document.getElementById('root')
);
p {
margin-top: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>

Radio button not working

I have created a radio component but when clicked it does'nt show checked
here is the code
import React from 'react';
import classnames from 'classnames';
const RadioButton = (field) => {
const inputClasses = classnames('form-group has-feedback ',{
'has-error': field.meta.touched && field.meta.error,
});
return(
<div className={inputClasses}>
<label className="radio-inline custom-radio nowrap">
<input
disabled={field.disabled}
type="radio"
name={field.input.name}
value={field.input.value}
defaultChecked={field.defaultChecked}
{...field.input}
/>
<span>{field.label}</span>
</label>
</div>
);
};
export default RadioButton;
here is the field:
<Field
label="True"
component={RadioButton}
name="True"
type="radio"
value={true}
defaultChecked={ true }
/>
<Field
label="False"
component={RadioButton}
name="False"
type="radio"
value={false}
defaultChecked={ false }
/>
this is the warning i am getting on console:
Warning: RadioButton contains an input of type radio with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props
can anyone help me out with this?
You should take a look at the official documentation, specifically the sections regarding Controlled Components and Uncontrolled Components.
Controlled Component
Basically, with controlled components you let React manage the value of said element.
An input form element whose value is controlled by React in this way is called a "controlled component".
To create a controlled component you need a state variable which stores its value, as well as a function which mutates its value based on some event (click, input, etc).
Here's a simple example:
class ControlledComponentDemo extends React.Component {
constructor() {
super();
this.state = {
input: "",
radio: null,
checkbox: []
};
}
changeInput = (e) => {
this.setState({input: e.target.value});
}
changeRadio = (id) => {
this.setState({radio: id});
}
changeCheckbox = (id) => {
let arr = this.state.checkbox.slice();
if(arr.indexOf(id) >= 0) {
arr.splice(arr.indexOf(id), 1);
} else {
arr.push(id);
}
this.setState({checkbox: arr});
}
render() {
return(
<form>
<input type="text" value={this.state.input} onChange={this.changeInput} />
<br /><br />
<input type="radio" name="myRadio" checked={this.state.radio === 0} onChange={this.changeRadio.bind(this, 0)} />
<input type="radio" name="myRadio" checked={this.state.radio === 1} onChange={this.changeRadio.bind(this, 1)} />
<br /><br />
<input type="checkbox" name="myCheckbox" checked={this.state.checkbox.indexOf(0) >= 0} onChange={this.changeCheckbox.bind(this, 0)} />
<input type="checkbox" name="myCheckbox" checked={this.state.checkbox.indexOf(1) >= 0} onChange={this.changeCheckbox.bind(this, 1)} />
</form>
);
}
}
ReactDOM.render(<ControlledComponentDemo />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Uncontrolled Component
As the name suggests, in uncontrolled components React does not manage the value of the form elements. Instead, these are managed by the DOM directly the "traditional way".
In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.
Create an uncontrolled component is easy:
class UncontrolledComponentDemo extends React.Component {
render() {
return(
<form>
<input type="text" />
<br /><br />
<input type="radio" name="myRadio" />
<input type="radio" name="myRadio" />
<br /><br />
<input type="checkbox" name="myCheckbox" />
<input type="checkbox" name="myCheckbox" />
</form>
);
}
}
ReactDOM.render(<UncontrolledComponentDemo />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
The issue with your code is that you have a mixed syntax of controlled and uncontrolled components.
In controlled components the value is defined in the state and passed into the value or checked props (depending on the input type) as I demonstrated above.
Since uncontrolled components are not managed by the state we shouldn't pass anything in to the value or checked props either. It doesn't make sense to do that because the DOM manages that on its own.
What we can do though is tell the DOM the initial value of said element. For example a text input could have something already typed in, or a checkbox already checked. We do this with the defaultValue prop.
And this is the mixup that you have done. You are using both defaultValue and checked here. Hence the warning:
Warning: RadioButton contains an input of type radio with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props.
I should also mention that controlled components are the ones recommended by React. You should still read the documentation sections I linked above.
Please use this!
It's working perfectly!
<label>
<input type="radio" defaultChecked={true} disabled={false} value={YOUR_Value} />
{this.state.content}
</label>

checkbox hiding and showing component - react

I am building a small feature that has a checkbox styled as slider that, when turned on and off, should display another component - BatchWidget. The way I have it currently set up, it works on initial page load, and then hides as intended. However, when I go to "toggle" it back on to show the component again, it does not work. Is there an easy solution to this?
const Slider = (props) => {
return (
<div className="slider-container">
<label className="switch">
<input type="checkbox" checked={props.checked} onClick= {props.showWidget} />
<span className="slider round" />
</label>
<p className="batch-slider-title"> Batch Widget </p>
</div>
);
};
const Settings = ({showSlider}) => {
return (
<div className="settings">
<i className="icon-gear" onClick={() => showSlider()} />
</div>
);
}
class WidgetContainer extends Component {
constructor() {
super();
this.state = {
checked: true,
isSliderDisplayed: false,
};
this.showWidget = this.showWidget.bind(this);
this.showSlider = this.showSlider.bind(this);
}
showWidget() {
this.setState({
checked: !this.state.checked,
});
}
showSlider() {
this.setState({
isSliderDisplayed: !this.state.isSliderDisplayed,
});
}
render() {
const displayBatchWidget = this.state.checked ? <BatchWidget /> : null;
const displaySlider = this.state.isSliderDisplayed ? <Slider checked={this.state.checked} showWidget={this.showWidget} /> : null;
return (
<div>
<Settings showSlider={this.showSlider} />
{displaySlider}
{displayBatchWidget}
</div>
);
}
}
When I try to debug, it shows:
Warning: Failed form propType: You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`. Check the render method of `Slider`.
I think it is self-explanatory.
I've changed the line with checkbox to:
<input type="checkbox" checked={props.checked} onChange= {props.showWidget} />
Now, the batchWidget should hide and show on each click.
Reactjs matrial ui table check box hide
first do
<Table selectable={false}>
<TableHeader displaySelectAll={false} adjustForCheckbox={false}>
this method hide table header check box
then do <TableBody displayRowCheckbox={false}>
it hide table body checkbox
it work perfect.
reactjs

Resources