MDC Web Textfield component outline disappearing - javascript

I am having an issue with MDC web textfield component. The issue is that the outline does not stay when I click on the textfield to type in an input. See below for the pug and javascript code :
div.mdc-layout-grid__cell--span-4.mdc-layout-grid__cell--span-12-phone.mdc-layout-grid__cell--span-12-tablet
label.mdc-text-field.mdc-text-field--filled
span.mdc-text-field__ripple
span.mdc-floating-label(id="first_name") First Name :
input.mdc-text-field__input(type="text" aria-labelledby="first_name")
span.mdc-line-ripple
div.mdc-layout-grid__cell--span-4.mdc-layout-grid__cell--span-12-phone.mdc-layout-grid__cell--span-12-tablet
label.mdc-text-field.mdc-text-field--outlined
span.mdc-notched-outline
span.mdc-notched-outline__leading
span.mdc-notched-outline__notch
span.mdc-floating-label(id="last_name") Surname :
span.mdc-notched-outline__trailing
input.mdc-text-field__input(type="text" aria-labelledby="last_name")
const textFields = [].map.call(document.querySelectorAll('.mdc-text-field'), function (el) {
return new mdc.textField.MDCTextField(el);
});
const notchedOutline = [].map.call(document.querySelectorAll('.mdc-notched-outline'), function (el) {
return new mdc.notchedOutline.MDCNotchedOutline(el);
});
const floatingLabel = [].map.call(document.querySelectorAll('.mdc-floating-label'), function (el) {
return new mdc.floatingLabel.MDCFloatingLabel(el);
});
const lineRipple = [].map.call(document.querySelectorAll('.mdc-line-ripple'), function (el) {
return new mdc.lineRipple.MDCLineRipple(el);
});
```[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/E8t9g.png

The primary color of the website was white and this made it look as though it disappeared when it was actually just white. When you change the primary color of the website, it reflects on the textfield as well.

Related

ReactJS: How To Get Input Value From The Prompt Box And Update It To Database

I'm building a MERN app, I want to let user edit the food name in the prompt box by clicking on the Edit button.
I was following the instructions in this link: [https://stackoverflow.com/questions/54993218/reactjs-using-alert-to-take-input-from-user]
The issue is when I click on the Edit button and type in the prompt then click OK, it will receive the null value for the first time, but it won't update the database.
And then when I click the Edit button again, without input anything to it then press OK, it will receive the value from the first time input and update it to database (like a delay).
What I want is: when click on the Edit button, it will display the prompt box and take the value from the prompt box and update to the database when the user clicks OK.
Is there any way I can fix this? Thank you everyone!
Here's my demo: gif
Here's my code:
function FoodListTable(props) {
/* Definition of handleClick in component */
const [newFoodName, setNewFoodName] = useState("")
const handleEdit = () => {
const enteredFood = prompt('Please enter your new food:')
setNewFoodName(enteredFood)
console.log(newFoodName)
if (newFoodName) {
Axios.put("https://mern-lefood.herokuapp.com/update", {
newFoodName: newFoodName,
id: props.val._id
})
}
}
return (
<button onClick={handleEdit}>Edit</button>
)
}
React this.setState, and useState does not make changes directly to the state object.
React this.setState, and React.useState create queues for React core to update the state object of a React component.
So the process to update React state is asynchronous for performance reasons. That’s why changes don’t feel immediate.
Try below code that's works !
function FoodListTable(props) {
/* Definition of handleClick in component */
const [newFoodName, setNewFoodName] = useState("");
const handleEdit = () => {
const enteredFood = prompt('Please enter your new food:');
setNewFoodName(enteredFood);
if (enteredFood) {
Axios.put("https://mern-lefood.herokuapp.com/update", {
newFoodName: enteredFood,
id: props.val._id
})
}
}
return (
<button onClick={handleEdit}>Edit</button>
)
}
For more detail Click here

How can I scroll right when inserting a character in draft js?

With draft-js and a styled component, I made an inline input intended for a calculator. When I type into it with a keyboard, it works as expected:
When I press the plus button, a "+" is added to the text, but the view doesn't scroll:
Here's the behavior and the code in a codesandbox:
https://codesandbox.io/s/charming-brattain-mvkj3?from-embed=&file=/src/index.js
How can I get the view to scroll when text is added programmatically like that?
At long last, I figured out a solution. I added this to the calculator input component:
const shell = React.useRef(null);
const [scrollToggle, setScrollToggle] = React.useState(
{ value: false }
);
React.useEffect(() => {
const scrollMax = shell.current.scrollWidth - shell.current.clientWidth;
shell.current.scrollLeft += scrollMax;
}, [scrollToggle]);
const scrollToEnd = () => {
setScrollToggle({ value: !scrollToggle.value });
};
Then at the end of the insertChars function I added scrollToEnd();.
And I set ref={shell} on <InputShell>

How to add text on border with css for input field using React JS?

I want to create an input box like below,
using css, however am not able to find anything on how to do the text on border for input fields anywhere at all
I tried using but am unable to create the input box as shown above.
I am very much stuck here, it would be a great help if anyone could suggest anyway to create an input field like shown above.
Thank you in advance.
You can use react-native-material-textfield library and need some customization. There is a prop renderLeftAccessory which can render your left view like country code here. Try example code here
import React, { Component } from 'react';
import {
TextField,
FilledTextField,
OutlinedTextField,
} from 'react-native-material-textfield';
class Example extends Component {
fieldRef = React.createRef();
onSubmit = () => {
let { current: field } = this.fieldRef;
console.log(field.value());
};
formatText = (text) => {
return text.replace(/[^+\d]/g, '');
};
render() {
return (
<OutlinedTextField
label='Phone number'
keyboardType='phone-pad'
formatText={this.formatText}
onSubmitEditing={this.onSubmit}
ref={this.fieldRef}
/>
);
}
}

How to generate an array for each input value from textBox in reactJs

I have a textBox which will allow me to enter the building name and after I click on 'Add Building' button, it takes the value and passes it to the next page.So, in my screenshot below, the values 'AbsBuildingOne' and 'AbsBuildingTwo' comes from the textBox input.So, currently I am able to pass a single value from the textBox to the next page, but I am not able to understand if I want to enter the second building how do I save the previous value in this page and add the second value below it. I guess I have to do it with arrays, but I am not able to figure it out how to proceed.
Currently, my code looks as shown below for passing the single value.I have added a state:
this.state = {
textBoxValue: '',
};
So, in my textBox the onUpdateHandler function looks like this:
onClickAddBuildingTextBoxHandler = (inputData) => {
this.setState({ textBoxValue: inputData.value});
}
My textBox component looks like this.Its a custom textBox designed for the project:
<SceTextBox
placeholder='Enter Building Name'
id='AddBuilding'
type='buildingName'
maxLength='40'
onTextUpdatedHandler={this.onClickAddBuildingTextBoxHandler.bind(this)}
forceValidate={this.state.forceValidate}
validator={app.appUtil.validator}
isError={this.state.textBoxEmptyError}
errorMsg={this.errorMessage}
/>
So, currently I am passing the value of this.state.textBoxValue to my next component where the building names are displayed.
So, how do I proceed with multiple values and how do I save all the building names? Also, I have to delete the building name when i click on close icon. So do I have to work with push/pop in array? Someone please guide me with this.
Edit 1:
My new state looks like this:
this.state = {
buildingNames: {
[id++]: ''
}
};
Both my functions are:
onClickAddBuildingButtonHandler = () => {
const { buildingNames } = this.state;
this.setState({
buildingNames: {
...buildingNames,
[id++]:''
}
});
if (!this.state.selectedOptions) {
this.setState({ isRadioEmptyError: true });
if (!this.state.buildingNames.id) {
this.setState({ textBoxEmptyError: true });
}
}
if (this.state.selectedOptions && this.state.buildingNames) {
this.props.navigateToAddBuilding(this.state.buildingNames);
}
}
onClickAddBuildingTextBoxHandler = (inputData) => {
const { buildingNames } = this.state;
this.setState({
buildingNames:{
...buildingNames,
[inputData.id] : inputData.value
}
});
}
To get an array of values from a textarea you can use the this.state.value.split('\n') to separate split the string on each new line producing an array for you.
Below is a very simple example demonstrating its effectiveness. Just type in the textarea and look at the console. Once you make a new line you'll see a second element appears in the array.
function handleKeyUp() {
const textarea = document.getElementById('my-ta');
console.log(textarea.value.split('\n'));
}
<textarea id='my-ta' onKeyUp='handleKeyUp()'></textarea>
EDIT #1:
Here is a Code Sandbox Example 1 demonstrating how it is done. Type in the textarea, make a new line and type some more and then hit the toggle button. You'll see the values displayed and if you toggle back they're in the textarea still.
EDIT #2:
So here is another example of how something can be done. This will show you how to add an item to a list. Code Sandbox Example 2
I'm going to leave it up to you to combine the two methods.

document.execCommand ('copy') don't work in React

I have the function below that is called on click of a button . Everything works well, but the document.execCommand ('copy') simply does not work.
If I create another button and call only the contents of if in a separate function, it works well.
I have already tried calling a second function inside the first one, but it also does not work. the copy is only working if it is alone in the function.
Does anyone know what's going on?
copyNshort = () => {
const bitly = new BitlyClient('...') // Generic Access Token bit.ly
let txt = document.getElementById('link-result')
bitly.shorten(txt.value)
.then((res) => {
this.setState({ shortedLink: res.url })
if (this.state.shortedLink !== undefined) {
document.getElementById('link-result-shorted').select() // get textarea value and select
document.execCommand('copy') // copy selected
console.log('The link has been shortened and copied to clipboard!')
ReactDOM.render(<i className="fas fa-clipboard-check"></i>, document.getElementById('copied'))
}
console.log('Shortened link 👉🏼', res.url) // Shorted url
})
}
The problem is that the copy-to-clipboard functionality will only work as a direct result of a user's click event listener... This event cannot be virtualised and the execCommand will not work anywhere else than the immediate callback assigned to the event listener...
Because react virtualises and abstracts 'events' then that's very possibly where the problem lies and as suggested you should be using React's react-copy-to-clipboard.
You can use lib react-copy-to-clipboard to copy text.
import {CopyToClipboard} from 'react-copy-to-clipboard';`
function(props) {
return (
<CopyToClipboard text={'Text will be copied'}>
<button>Copy button</button>
</CopyToClipboard>
);
}
if you click button Copy button, it will copy the text Text will be copied
The lib react-copy-to-clipboard based on copy-to-clipboard does work for me, but if you want to copy the source into your own file, Some places need attention.
The code below works fine.
import React, { Component } from 'react'
class App extends Component {
render() {
return (
<div className="App">
<h1
onClick={e => {
const range = document.createRange()
const selection = document.getSelection()
const mark = document.createElement('span')
mark.textContent = 'text to copy'
// reset user styles for span element
mark.style.all = 'unset'
// prevents scrolling to the end of the page
mark.style.position = 'fixed'
mark.style.top = 0
mark.style.clip = 'rect(0, 0, 0, 0)'
// used to preserve spaces and line breaks
mark.style.whiteSpace = 'pre'
// do not inherit user-select (it may be `none`)
mark.style.webkitUserSelect = 'text'
mark.style.MozUserSelect = 'text'
mark.style.msUserSelect = 'text'
mark.style.userSelect = 'text'
mark.addEventListener('copy', function(e) {
e.stopPropagation()
})
document.body.appendChild(mark)
// The following line is very important
if (selection.rangeCount > 0) {
selection.removeAllRanges()
}
range.selectNodeContents(mark)
selection.addRange(range)
document.execCommand('copy')
document.body.removeChild(mark)
}}
>
Click to Copy Text
</h1>
</div>
)
}
}
export default App
import React, { Component } from 'react'
class App extends Component {
render() {
return (
<div className="App">
<h1
onClick={e => {
const mark = document.createElement('textarea')
mark.setAttribute('readonly', 'readonly')
mark.value = 'copy me'
mark.style.position = 'fixed'
mark.style.top = 0
mark.style.clip = 'rect(0, 0, 0, 0)'
document.body.appendChild(mark)
mark.select()
document.execCommand('copy')
document.body.removeChild(mark)
}}
>
Click to Copy Text
</h1>
</div>
)
}
}
export default App

Categories

Resources