How to catch selected text inside input? - reactjs

I have TextField(material-ui) and I need to catch what text user have selected.
For example I have text: I want to buy car.
User selected: want
How can I catch selected text and generate list component right after the text selection end?

Create an onchange function, and pass event parameter to the onchange function. This event parameter will hold the input element object, on doing event.target.value , you will get selected value. You can replace select with TextField.
function get_data(event){
alert(event.target.value);
}
<select id="data" onchange="get_data(event)">
<option value="one">Option 1 Here</option>
<option value="two">Option 2 Here</option>
</select>

import React, { Component } from 'react'
export default class Select extends Component {
constructor(props){
super(props);
this.state={
value:"",
}
this.handleChange=this.handleChange.bind(this);
}
handleChange(e){
this.setState({
[e.target.name]: e.target.value
})
}
render() {
console.log(this.state.value);
return (
<select id="data" value={this.state.value} name="value" onChange={this.handleChange}>
<option value="one">Option 1 Here</option>
<option value="two">Option 2 Here</option>
</select>
)
}
}
handleChange fire when option is selected! setting state.value to option value

So, basically 2 options
pass the onChange function to your input and get its value from event.target.value
you can use refs to get the DOM node and there you can also get the value of the input (https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element)

Related

React JS with Redux: How to pass e.target.value from one component to another

I have an input select that generated a value using an onChange method. However, I am trying to pass the selected value from this component to another component. This is how my code looks like now:
<Input type="select" name="selectInput" value={this.state.completeTask} onChange=.
{this.handleChangeCompleteTask} >
<option value="" disabled> Select Reason</option>
<option value="Task Completed"> Task Completed</option>
<option value="Task in Progress"> Task in Progress</option>
</Input>
The handleChangeCompleteTask is:
handleChangeCompleteTask = (e) => {
this.setState({ completeTask: e.target.value });
};
I also have an initial state for completeTask as:
state = {
completeTask: ''
};
The question is how can I pass completeTask current state as in this.state.nonCompletionReason and pass it to a different function in a different component.
The other component has a function that handles tasks as in:
handleTasks = (tasks) => {
this.props.tasks(tasks)
}
I would like to pass the
You will want to pass state.completeTask into the props of the other component like this: <OtherComponent completeTask={this.state.completeTask} />. Then the OtherComponent will have access via this.props.completeTask.

how to open a textfield and set its value on select some value in dropdown in react

I am trying to display a textbox based on some selected value in dropdown in react.
my code is
<label>
color:
<select value="Radish" onChange ={this.checkColor}>
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
<input type="text" name="project Id" id="project Id" style={{display:'none'}}/>
<label>
Onchange, the below function will be invoked.
CheckLayers(evt){
if(evt.target.value === 'Orange'){
this.setState({showField:true})
}
}
But I am not able to see the textbox. I tried to put condition based on showField but that's not working.
(this.state.showField)
<input type="text" name="project Id" id="project Id" style={{display:'none'}}/>
Please advice!!
There are a few things to check in your code.
First, with your current implementation of the <select> and <option> elements, the actual value on the <select> will never change because it is always set to "Orange". You need to also save the last selected <select> value in your component's state:
checkLayers(event) {
const { value } = event.target;
this.setState({
showField: value === "Orange",
selectedValue: value
});
};
And in your render method use the selectedValue accordingly:
render() {
return (
<label>
color
<select value={this.state.selectedValue} onChange={this.checkLayers}>
/* {your options} */
</select>
</label>
);
}
The next thing to check is the checkLayers method. Inside this method you are trying to access this. Since the <select>'s onChange callback is going to be called on a different context as your component (you can check this by logging this inside checkLayers). As a result of this, you need to bind the checkLayers method to your component's context. This can be done by explicitly binding the function when passing it as a callback or by defining the class method as an arrow function.
Binding option (in the render method):
<select value={selectedValue} onChange={this.checkLayers.bind(this)}>
Class method as Arrow function option:
class MyComponent extends React.Component {
...
checkLayers = (event) => {
const { value } = event.target;
this.setState({
showField: value === "Orange",
selectedValue: value
});
};
...
There is also an alternative option using arrow functions:
<select value={selectedValue} onChange={(event) => this.checkLayers(event)}>
You can learn more about thishere
The last thing to check is how you are trying to conditionally render the <input> element. Right now you are hardcoding the style as { display: 'none' }. You could change this based on the value of showField, but I think is it better only render the <input> when showField is true, like this:
render() {
const { selectedValue, showField } = this.state;
return (
<label>
color:
<select value={selectedValue} onChange={this.checkLayers.bind(this)}>
/* {your options} */
</select>
{showField ? (
<input
type="text"
name="project Id"
id="project Id"
/>
) : null}
</label>
);
}
Here we are using the ternary operator to decide if we render the element or we render nothing (using null).
You can see the final implementation here:
Comment if you have further questions, cheers!

React change initial state based on another field value

How can I change the initial state value of a field based on the input value of another field?
Here's my code:
import React from "react";
export class someComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
grade: "",
tuition: changeStateHere
};
}
render() {
<div>
<form onSubmit={this.someFunction.bind(this)}>
<select name="grade" onChange={this.onChange} value={this.state.grade}>
<option value="">Class</option>
<option value="Grade One">Grade One</option>
<option value="Grade Two">Grade Two</option>
<option value="Grade Three">Grade Three</option>
<option value="Grade Four">Grade Four</option>
<option value="Grade Five">Grade Five</option>
<option value="Grade Six">Grade Six</option>
</select>
<input
type="text"
name="tuition"
placeholder="Tuition"
value={this.state.tuition}
onChange={this.onChange}
/>
</form>
</div>;
}
}
I want to set a dynamic initial state value for tuition based on input option on the grade select field.
For example, if a user selects Grade One, the tuition value should be 15000; if Grade Two, the value should be '20000'; etc.
Is there any workaround dynamically changing the initial state value?
Everything inside of the constructor is run before render. You're not going to be able to set a different initial value to the state based on something inside the render method.
Also move away from binding functions in the render method. it would be better to use a class method someFunction = () => {} and then attach it inside the JSX as onSubmit={this.someFunction}
Each time the component re-renders another instance of someFunction is bound which will eventually lead to performance issues in the browser.
You need to handle the grade selection and evaluate the event.target.value of the select element. Based on this you can use a switch to this.setState both Tuition and whether or not the input field is disabled. You should use defaultValue instead of value so that when the user picks and option it sets the input to this.state.tuition
import React from "react";
export class someComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
grade: "",
gradeSelected: false,
tuition: 0,
};
}
handleGradeSelect = event => {
let newState = Object.assign({}, this.state) // duplicate state so you can mutate this copy
switch(event.target.value){ // evaluate the value of the select option
case 'Grade One':
newState.tuition = 15000
case 'Grade Two':
newState.tuition = 20000
// You get the picture
default:
newState.tuition = 0 // needs to have a default if no option
}
newState.gradeSelected = true
this.setState(newState)
}
render() {
<div>
<form onSubmit={this.someFunction.bind(this)}>
<select name="grade" onChange={event => this.handleChange(event)}>
<option disabled>Class</option>
<option value="Grade One">Grade One</option>
<option value="Grade Two">Grade Two</option>
<option value="Grade Three">Grade Three</option>
<option value="Grade Four">Grade Four</option>
<option value="Grade Five">Grade Five</option>
<option value="Grade Six">Grade Six</option>
</select>
<input
type="text"
name="tuition"
placeholder="Tuition"
value={this.state.tuition}
onChange={this.onChange}
disabled={!this.state.gradeSelected}
/>
</form>
</div>;
}
}

How to automaticaly setState in an onChange event in a select-dropdown, as currently the event is triggered only when the user clicks on the list?

Currently, the default state is empty and is updated only when the user clicks on the drop-down triggering the onChange event. How do I make it so that the item selected by default is also set to the state? So the first option is selected by default in the drop-down, and I'd like to set the first option in the state automatically.
this.state = { slug: '' }
<select>
data && data.map((datum, i) => { return (
<option
value={datum.id}
key={i}
onChange={e => this.setState({ slug: datum.slug })}>
{datum.name}
</option>
)})}
<select>
You can define the default value in the state
this.state = { slug: 'zero' }
and then tells react to set that value in the select
<select value={this.state.slug}>
<option value="zero">Zero</option>
<option value="one">One</option>
<option value="two">Two</option>
</select>
If you want to programmatically select the first value, you can write this.
<select>
data && data.map((datum, i) => {
const isSelected = this.state.slug === '' && i === 0;
return (
<option
selected={isSelected}
value={datum.id}
key={i}
onChange={}
>
{datum.name}
</option>
)})}
</selected>
If you want your state to reflect your default option, you can do that in the constructor of the component.
constructor(props){
super(props);
this.state = {
slug : this.props.data[0].id
}
}
After that you can use one of the solutions I mention before to handling the select component.
If you change data often, you can do that inside componentWillReceiveProps instead of constructor, but the idea it's the same.

How to set placeholder for dropdown in react js?

<select>
<option selected disabled>Select</option
I added an extra option with a disabled property, but this gives me the following warning:
Use the defaultValue or value props on select instead of setting
selected on option.
<select>
{this.props.optionarray.map(function(e){
return <option
value={e[self.props.unique]}
key={e[self.props.unique]}
>
{e[self.props.name]}
</option>
})}
</select>
optionarray is an array which is passed through props to be mapped on each index which has an object and I pass the key through props as well which was in the array. Everything is working here, it's just showing me the warning that I mentioned above.
How do I remove that or how do I set a perfect placeholder for a dropdown in react?
Reason is, React provide a better way of controlling the element by using states, so instead of using selected with option use the value property of select and define its value in the state variable, use the onChange method to update the state, Use it in this way:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '1'
};
}
render(){
return(
<select value={this.state.value} onChange={(e)=>{this.setState({value: e.target.value})}}>
<option value='1' disabled>Select</option>
{
[2,3,4].map((i,j)=>{
return <option key={i} value={i}>{i}</option>
})
}
</select>
);
}
}
How to set placeholder for dropdown?
According to Mozilla Dev Network, placeholder is not a valid attribute on a <select>. So in place of that you can you this also to render a default option:
<option default>Select</option>
Use of key as per DOC:
Keys help React identify which items have changed, are added, or are
removed. Keys should be given to the elements inside the array to give
the elements a stable identity.
Suggestion:
Whenever we create any ui dynamically in loop, we need to assign a unique key to each element, so that react can easily identify the element, it basically used to improve the performance.
Check the working example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '1'
};
}
render(){
return(
<select value={this.state.value} onChange={(e)=>{this.setState({value: e.target.value})}}>
<option value='1' disabled>Select</option>
{
[2,3,4].map((i,j)=>{
return <option key={i} value={i}>{i}</option>
})
}
</select>
);
}
}
ReactDOM.render(<App />, document.getElementById('container'));
<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='container'/>
Check the fiddle for working example: https://jsfiddle.net/29uk8fn0/
Functional Component
import { useState } from "react";
export default function DropdownComponent(props) {
const [formData, setFromData] = useState({
anyInput: "something",
dropdownInput: null,
});
return (
<>
anyInput: { formData.anyInput }
dropdownInput: { formData.dropdownInput }
<select name={"dropdownName"} onChange={ ({target})=> {
setFromData((prev)=> ({...prev, dropdownInput:target?.value}) );
}
}>
<option key='blankKey' hidden value >Placeholder Text for Select</option>
{
[2,3,4].map((i,j)=>{
return <option key={i} value={i}>{i}</option>
})
}
</select>
</>
)
}

Resources