Styling cannot be applied to button - React Hooks - react-hooks

I'm using a resuable component for button wherein i wanna pass the color and bgColorvia props, color gets applied but then the background color doesnt apply
const useStyles = makeStyles(theme => ({
button: {
//width:'100%',
margin: theme.spacing(1)
},
input: {
display: "none"
}
}));
export default function ContainedButtons(props) {
const classes = useStyles();
const btnStyle = {
color: props.color,
backgroundColor: props.bgClrRed
};
console.log(props);
return (
<div>
<Button
variant="contained"
style={{ backgroundColor: props.bgClrRed, color: props.color }}
fullWidth="true"
className={classes.button}
>
{props.name}
</Button>
<Button
variant="contained"
style={btnStyle}
fullWidth="true"
className={classes.button}
>
{props.name}
</Button>
</div>
);
}
I'm missing something I don't know what can anyone please lemme know
Updates
import ContainedButtons from '../container/buttonsControl';
import css from '../variable.scss';

Try a spread operator:
style={...btnStyle}

Related

Adding an image to react-google-maps InfoWindow content

Note: I am using the "react-google-maps" api and this is how my current InfoWindow is set up
{showingInfoWindow && selectedPlace === spot._id && <InfoWindow
className="info-window"
onCloseClick={onInfoWindowClose}
position={{lat: spot.lat, lng: spot.lng}}
>
<div className="iw-container">
<strong className="iw-title">{spot.name}</strong>
<div className="iw-content">
{spot.location}
<div>Added By: {currentUser.displayName === spot.user ? "Me" : spot.user}</div>
<div>{spot.type}</div>
<div>{spot.desc}</div>
<div>{moment(spot.createdAt).format("MMM Do YYYY")}</div>
{/* <img src={`/server/uploads/${spot.createdAt.split('.')[0]+"Z"}.jpg`}> </img> */}
</div>
</div>
</InfoWindow>}
I was wondering how I add an image to the infowindow, I've seen it done with a content prop in other api's, and react-google-maps docs has a prop for updating the content, but I can't find how to set the content on their documentation. Any help is appreciated!
You can directly add an <img> tag as a child of the <infowindow>
Sample code snippet:
import React, { Component } from 'react';
import {
withGoogleMap,
GoogleMap,
Marker,
InfoWindow
} from 'react-google-maps';
class Map extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: false
};
}
handleToggleOpen = () => {
this.setState({
isOpen: true
});
};
handleToggleClose = () => {
this.setState({
isOpen: false
});
};
render() {
const GoogleMapExample = withGoogleMap(props => (
<GoogleMap
defaultCenter={{ lat: -33.86882, lng: 151.209296 }}
defaultZoom={13}
>
<Marker
key={this.props.index}
position={{ lat: -33.86882, lng: 151.209296 }}
onClick={() => this.handleToggleOpen()}
>
{this.state.isOpen && (
<InfoWindow
onCloseClick={this.props.handleCloseCall}
>
<img src="https://www.australia.com/content/australia/en/places/sydney-and-surrounds/guide-to-sydney/jcr:content/mainParsys/imagecontainer/imageContainerParsys/imagehighlights_835593945/ImageTile/imageHighlightsSrc.adapt.740.medium.jpg" width="250px" height="250px"/>
</InfoWindow>
)}
</Marker>
</GoogleMap>
));
return (
<div>
<GoogleMapExample
containerElement={<div style={{ height: `500px`, width: '500px' }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
}
export default Map;
I figured out the problem: I needed to use a self-closing img tag.
instead of
<img src="..."> </img>
it must be
<img src="..."/>

Image not loading in React Native when I use require but loads when I load from URL

When I try to load an image by using require, the image does not load but when I load the same image from a URL, the image loads. Here is the snippet of code that I am calling the image from
class Home extends React.Component {
render() {
return (
<ScrollView
noSpacer={true}
noScroll={true}
style={styles.container}
showVerticalSCrollIndicator = {false}
showHorizontalScrollIndicator = {false}
>
{this.state.loading ? (
<ActivityIndicator
style={[styles.centering, styles.gray]}
color="#5d38aa"
size="large"
/>
) : (
<div>
<Header title={this.state.user.name} />
<div id='image'>
<Image
source={require('./arrow.png')}
style={styles.image}
/>
</div>
</div>
)}
</ScrollView>
);
}
}
The image is loaded here
<Image
source={require('./arrow.png')}
style={styles.image}
/>
Please make sure that you give the right path to your image.
You can use the source as an object:
<Image source={{ uri: 'something.jpg' }} />
But what you have should work, check your path.
There were few errors here and there, I think you were trying to port ReactJS code to RN and not surprisingly there were few slip-ups like you used div instead and View and small things like that, also boxShadow was not working so I removed that.
After a few tweaks code is working and images are loading.
As I stated earlier, I have omitted the User component and sanityClient, you can implement them later.
Here is the working home.js after changes.
import React from "react";
import {
ScrollView,
ActivityIndicator,
StyleSheet,
Image,
ImageBackground,
View,
} from "react-native";
// import UserList from "./user-list";
import Header from "./header";
// import sanityClient from "";
// import BackButton from "./back-button";
// import User from "./user";
// import {Asset} from 'expo-asset';
// const imageURI = Asset.fromModule(require('./arrow.png')).uri;
// const image = require("./assets/aoeu.jpg");
class Home extends React.Component {
state = {
user: {},
loading: true,
};
componentDidMount() {
// TODO: get users
this.getUser();
}
async getUser() {
// sanityClient
// .fetch(
// `*[ _type == "user" && emailAddress.current == "dwight#viamaven.com"]`
// )
// .then((data) => {
// console.log(data);
// this.setState({ user: data[0], loading: false });
// console.log(this.state.user);
// })
// .catch((err) => console.error(err));
// const res = await fetch("https://randomuser.me/api/?results=20");
// const { results} = await res.json();
// // console.log(results)
// this.setState({users: [...results], loading: false});
}
render() {
return (
<ScrollView
noSpacer={true}
noScroll={true}
style={styles.container}
showVerticalSCrollIndicator={false}
showHorizontalScrollIndicator={false}
>
{!this.state.loading ? (
<ActivityIndicator
style={[styles.centering, styles.gray]}
color="#5d38aa"
size="large"
/>
) : (
<View>
<Header title={"Spidy"} />
<View id="image">
<Image source={require("./arrow.png")} style={styles.image} />
</View>
{/* <User /> */}
</View>
)}
</ScrollView>
);
}
}
var styles = StyleSheet.create({
container: {
backgroundColor: "white",
width: 375,
height: 812,
// top: '50px',
},
centering: {
alignItems: "center",
justifyContent: "center",
padding: 8,
height: "100vh",
},
image: {
width: 50,
height: 50,
marginRight: 20,
// boxShadow: "0px 1px 2px 0px rgba(0,0,0,0.1)",
// boxShadow: "10px 10px 17px -12px rgba(0,0,0,0.75)",
},
});
export default Home;
Zip file containing all the changes: src
Output:

reducer case set value delayed response

When I dispatch "REMOVE_TODO" on button click it does what I want it to do, the problem I'm having is that when it executes. It doesn't return the correct current array length.
Now when I click an item, it will dispatch "TOGGLE_TODO" which will change the font color and put a line-through the text.
Now while toggled and I click the "Clear Completed" button, it toggles "REMOVE_TODO" and works fine. It removes the items toggled. The problem I'm having is that The number doesn't reflex the current amount of items left in the list when I click the button once..
However if I click the button once more (or however many more times) the number updates to the correct total
This is my app code
import React, { useState, useReducer } from 'react';
import { Reducer } from './reducers/reducer';
import './App.css';
function App() {
const [{ todos, todoCount }, dispatch] = useReducer(Reducer, {
todos: [],
todoCount: 0,
completedCount: 0
});
const [text, setText] = useState("");
return (
<div className="App">
<header className="App-header">
<div>ToDo List [ <span style={{color: '#61dafb', margin: '0px', padding: '0px'}}>{ todoCount }</span> ]</div>
<div>
{ todos.map((todo, index) => (
<div
key={index}
onClick={() => dispatch(
{ type: "TOGGLE_TODO", index }
)}
style={{
fontFamily: 'Tahoma',
fontSize: '1.5rem',
textDecoration: todo.completed ? 'line-through' : "",
color: todo.completed ? '#61dafb' : 'dimgray',
cursor: 'pointer'
}}
>
{ todo.text }
</div>
))
}
<form
onSubmit={e => {
e.preventDefault();
text.length === 0 ? alert("No Task To Add!") : dispatch({ type: "ADD_TODO", text });
setText("");
}}
>
<input
type="text"
name="input"
value={ text }
onChange={e => setText(e.target.value)}
/><br />
<button>
Add
</button>
</form>
<button onClick={() => {dispatch({ type: "REMOVE_TODO" })}}>
Clear Completed
</button>
</div>
</header>
</div>
);
}
export default App;
and this is my reducer code
export const Reducer = (state, action) => {
switch (action.type) {
case 'ADD_TODO':
return {
todos: [...state.todos, { text: action.text, completed: false, id: Date.now() }],
todoCount: state.todoCount + 1,
completedCount: 0
};
case 'TOGGLE_TODO':
return {
todos: state.todos.map((todo, index) => index === action.index ? { ...todo, completed: !todo.completed } : todo),
todoCount: state.todoCount,
completedCount: 0
};
case 'REMOVE_TODO':
return {
todos: state.todos.filter(t => !t.completed),
todoCount: state.todos.length
}
default:
return state;
};
};
Does anyone have any idea what I'm doing wrong, or what I'm not doing? Thanks in advance!
Remove "todoCount" from reducer, then derive count using "todos":
<div>
ToDo List [{" "}
<span style={{ color: "#61dafb", margin: "0px", padding: "0px" }}>
{todos.filter((todo) => !todo.completed).length}
</span>{" "}
]
</div>
View in CodeSandbox here

Making the CKEditor 5 inline placeholder widget editable

I've added the placeholder widget to my CKEditor 5 build. However I don't like that I can't change the text after it is inserted. I tried removing isObject from the schema but that didn't do anything. I'd appreciate it if someone could show me how this can be achieved.
In version 4 the edit of the text is done via popup called by double clicking on the placeholder: https://ckeditor.com/cke4/addon/placeholder
In version 5 the placeholder was not fully implemented intentionally
"We didn't decide, though to implement a ready-to-use placeholder feature as it's usually needed to work differently in various systems"
https://github.com/ckeditor/ckeditor5/issues/871
So the only thing you can do is to implement the function you are missing yourself. I suggest looking at how version 4 does and understanding if it is applicable to version 5.
I have implemented it just with additional HTML block and control it with state (in my case I'm using React).
const CKInlineEditorField = ({
defaultValue = '',
onChange,
placeholder = '',
}) => {
const [showPlaceholder, setShowPlaceholder] = useState(false);
const { t } = useTranslation();
useEffect(() => {
if (!defaultValue) {
setShowPlaceholder(true);
}
}, [defaultValue]);
return (
<div>
<Paper variant="outlined" className="InlineEditor">
<div className="InlineEditor__placeholder">
{showPlaceholder && `${t(placeholder)}...`}
</div>
<div className="InlineEditor__editor">
<CKEditor
editor={InlineEditor}
data={defaultValue}
onChange={(event, editor) => {
const data = editor.getData();
setShowPlaceholder(!data);
}}
onBlur={(event, editor) => {
const data = editor.getData();
onChange(data);
}}
/>
</div>
</Paper>
</div>
);
};
And SCSS file:
.InlineEditor {
background-color: #eee;
position: relative;
&__placeholder {
position: absolute;
top: 15px;
left: 10px;
z-index: 0;
}
&__editor {
position: relative;
z-index: 2;
}
}

How to set the height of CKEditor 5 (Classic Editor)

In CKEditor 4 to change the editor height there was a configuration option: config.height.
How do I change the height of CKEditor 5? (the Classic Editor)
Answering my own question as it might help others.
CKEditor 5 no longer comes with a configuration setting to change its height.
The height can be easily controlled with CSS.
There is one tricky thing though, if you use the Classic Editor:
<div id="editor1"></div>
ClassicEditor
.create( document.querySelector( '#editor1' ) )
.then( editor => {
// console.log( editor );
} )
.catch( error => {
console.error( error );
} );
Then the Classic Editor will hide the original element (with id editor1) and render next to it. That's why changing height of #editor1 via CSS will not work.
The simplified HTML structure, after CKEditor 5 (the Classic Editor) renders, looks as follows:
<!-- This one gets hidden -->
<div id="editor1" style="display:none"></div>
<div class="ck-reset ck-editor..." ...>
<div ...>
<!-- This is the editable element -->
<div class="ck-blurred ck-editor__editable ck-rounded-corners ck-editor__editable_inline" role="textbox" aria-label="Rich Text Editor, main" contenteditable="true">
...
</div>
</div>
</div>
In reality the HTML is much more complex, because the whole CKEditor UI is rendered. However the most important element is the "editing area" (or "editing box") marked with a ck-editor__editable_inline class:
<div class="... ck-editor__editable ck-editor__editable_inline ..."> ... </div>
The "editing area" is the white rectangle where one can enter the text. So to style / change the height of the editing area, it is enough to target the editable element with CSS:
<style>
.ck-editor__editable_inline {
min-height: 400px;
}
</style>
Setting the height via a global stylesheet.
Just add to your common .css file (like style.css):
.ck-editor__editable {
min-height: 500px;
}
In the case of ReactJS.
<CKEditor
editor={ClassicEditor}
data="<p>Hello from CKEditor 5!</p>"
onInit={(editor) => {
// You can store the "editor" and use when it is needed.
// console.log("Editor is ready to use!", editor);
editor.editing.view.change((writer) => {
writer.setStyle(
"height",
"200px",
editor.editing.view.document.getRoot()
);
});
}}
/>
editor.ui.view.editable.editableElement.style.height = '300px';
From CKEditor 5 version 22 the proposed programmatic solutions are not working. Here it is how I get the work done:
ClassicEditor.create( document.querySelector( '#editor' ) )
.then( editor => {
editor.ui.view.editable.element.style.height = '500px';
} )
.catch( error => {
console.error( error );
} );
.ck-editor__editable {min-height: 500px;}
<div>
<textarea id="editor">Hi world!</textarea>
</div>
<script src="https://cdn.ckeditor.com/ckeditor5/22.0.0/classic/ckeditor.js"></script>
Add this to your stylesheet:
.ck-editor__editable {
min-height: 200px !important;
}
If you wish to do this programatically, the best way to do it is to use a Plugin. You can easily do it as follows. The following works with CKEditor 5 version 12.x
function MinHeightPlugin(editor) {
this.editor = editor;
}
MinHeightPlugin.prototype.init = function() {
this.editor.ui.view.editable.extendTemplate({
attributes: {
style: {
minHeight: '300px'
}
}
});
};
ClassicEditor.builtinPlugins.push(MinHeightPlugin);
ClassicEditor
.create( document.querySelector( '#editor1' ) )
.then( editor => {
// console.log( editor );
})
.catch( error => {
console.error( error );
});
Or if you wish to add this to a custom build, you can use the following plugin.
class MinHeightPlugin extends Plugin {
init() {
const minHeight = this.editor.config.get('minHeight');
if (minHeight) {
this.editor.ui.view.editable.extendTemplate({
attributes: {
style: {
minHeight: minHeight
}
}
});
}
}
}
This adds a new configuration to the CKEditor called "minHeight" that will set the editor minimum height which can be used like this.
ClassicEditor
.create(document.querySelector( '#editor1' ), {
minHeight: '300px'
})
.then( editor => {
// console.log( editor );
} )
.catch( error => {
console.error( error );
} );
I tried to set the height and width on the config but it just didn't work on the classic Editor.
I was able to change the height of the editor programmatically on Vue by doing this.
mounted() {
const root = document.querySelector('#customer_notes');
ClassicEditor.create(root, config).then(editor=>{
// After mounting the application change the height
editor.editing.view.change(writer=>{
writer.setStyle('height', '400px', editor.editing.view.document.getRoot());
});
});
}
Use css:
.ck.ck-editor__main .ck-content {
height: 239px;
}
Add this to your global stylesheet, this will increase the size of the CKEditor :)
.ck-editor__editable_inline {
min-height: 500px;
}
Just add it to the style tag.
<style>
.ck-editor__editable
{
min-height: 150px !important;
max-height: 400px !important;
}
</style>
As for configuring the width of the CKEditor 5:
CKEditor 5 no longer comes with a configuration setting to change its width but its width can be easily controlled with CSS.
To set width of the editor (including toolbar and editing area) it is enough to set width of the main container of the editor (with .ck-editor class):
<style>
.ck.ck-editor {
max-width: 500px;
}
</style>
Simply you can add this to your CSS file
.ck-editor__editable {min-height: 150px;}
Put this CSS in your global CSS file and the magic will happen. CkEditor is full of unsolved mysteries.
.ck-editor__editable_inline {
min-height: 400px;
}
Use max-height and min-height both. Beacuse max-height give scroll bar option after reached maximum mention height. Where min-height give static height to <textarea>.
.ck-editor__editable {
max-height: 400px; min-height:400px;}
If its in latest version of Angular say 12 or 12+. We can add below style to your components style file.
:host ::ng-deep .ck-editor__editable_inline { min-height: 300px; }
If you use jQuery and the CKEditor 5 has to be applied to a textarea, there is a "quick and dirty" solution.
The condition:
<textarea name='my-area' id='my_textarea_id'>
If you use jQuery the Editor call could be:
var $ref=$('#my_textarea_id');
ClassicEditor
.create( $ref[0] ,{
// your options
} )
.then( editor => {
// Set custom height via jQuery by appending a scoped style
$('<style type="text/css" scoped>.ck-editor .ck-editor__editable_inline {min-height: 200px !important;}</style>').insertAfter($ref);
} )
.catch( error => {
console.error( error );
} );
In other words, after rendering, you can address the same element used to build the editor and append after a scoped style tag with containing the custom height.
$('<style type="text/css" scoped>.ck-editor .ck-editor__editable_inline {min-height: 200px !important;}</style>').insertAfter($ref);
If you like to use a function (or some class method) to do this, you need something like this:
var editorBuildTo = function(id,options){
var options=options || {};
//Height represents the full widget height including toolbar
var h = options.height || 250; //Default height if not set
var $ref = $('#'+id);
h=(h>40?h-40:h);//Fix the editor height if the toolbar is simple
ClassicEditor
.create( $ref[0] ,{
// your options
} )
.then( editor => {
// Set custom height via jQuery
$('<style type="text/css" scoped>.ck-editor .ck-editor__editable_inline {min-height: '+h+'px !important;}</style>').insertAfter($ref);
} )
.catch( error => {
console.error( error );
} );
}
editorBuildTo('my_textarea_id',{
height:175,
// other options as you need
});
This works well for me
1.resource/assets/js/app.js
=================================
2.paste this code
=================================
require('./bootstrap');
//integrate
window.ClassicEditor = require('#ckeditor/ckeditor5-build-classic');
============================================
3.write on terminal
============================================
npm install --save #ckeditor/ckeditor5-build-classic
npm run watch
=======================================
4.in blade file
=======================================
<!DOCTYPE html>
<html lang="en">
<title></title>
<body>
<form action="{{route('admin.category.store')}}" method="post" accept-charset="utf-8">
#csrf
<div class="form-group row">
<div class="col-sm-12">
<label class="form-control-label">Description:</label>
<textarea name="description" id="editor" class="form-control" row="10" cols="80"></textarea>
</div>
</div>
</form>
<script>
$(function () {
ClassicEditor
.create( document.querySelector( '#editor' ), {
toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote' ],
heading: {
options: [
{ model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
{ model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' },
{ model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' }
]
}
} )
.catch( error => {
console.log( error );
} );
})
</script>
</body>
</html>
click to show image here
Building on #Jaskaran Singh React solution. I also needed to ensure it was 100% height to it's parent. I achieved this by assigning a ref called "modalComponent" and further adding this code:
editor.editing.view.change(writer => {
let reactRefComponentHeight = this.modalComponent.current.offsetHeight
let editorToolbarHeight = editor.ui.view.toolbar.element.offsetHeight
let gapForgiveness = 5
let maximizingHeight = reactRefComponentHeight - editorToolbarHeight - gapForgiveness
writer.setStyle(
'height',
`${maximizingHeight}px`,
editor.editing.view.document.getRoot()
)
})
This CSS Method works for me:
.ck-editor__editable {
min-height: 400px;
}
I resolve this just adding in my layout page
<style>
.ck-content{
height: 250px;
}
</style>
Hope i help someone :D
For this particular version https://cdn.ckeditor.com/4.16.0/standard/ckeditor.js,
the below code block worked for me.
.cke_contents { height: 500px !important; }
I guess the difference is just the fact that is it in plural.
In my case it worked for me
Add a ck class and write style like below:
<style>
.ck {
height: 200px;
}
</style>
Using plugin here I came up with this
let rows: number;
export class MinHeightPlugin {
constructor(public editor) {
}
init = function () {
this.editor.ui.view.editable.extendTemplate({
attributes: {
style: {
minHeight: (rows * 40) + 'px',
}
}
});
};
}
export const MinHeightPluginFactory = (rowss: number): typeof MinHeightPlugin => {
rows = rowss;
return MinHeightPlugin;
};
and the usage(4 rows each rows is considered 40px height):
this.editor.builtinPlugins.push(MinHeightPluginFactory(4));
I couldn't manage to make rows variable local to MinHeightPlugin, does anyone know how to do it?
.ck-editor__editable_inline {
min-height: 400px;
}
This makes height change for every editor used across all components. So it doesn't work in my case.
In Case of react js
<CKEditor
toolbar = {
[
'heading',
'bold',
'Image'
]
}
editor={ClassicEditor}
data={this.state.description}//your state where you save data
config={{ placeholder: "Enter description.." }}
onChange={(event, editor) => {
const data = editor.getData();
this.setState({
description : data
})
}}
onReady={(editor)=>{
editor.editing.view.change((writer) => {
writer.setStyle(
//use max-height(for scroll) or min-height(static)
"min-height",
"180px",
editor.editing.view.document.getRoot()
);
});
}}
/>
In order to enable both rich text editor and source mode to have the same height, use the following CSS:
.ck-source-editing-area,
.ck-editor__editable {
min-height: 500px;
}
.ck-editor__main {
height: 500px;
min-height: 500px;
max-height: 500px;
overflow-y: scroll;
border: 1px solid #bbbbbb;
}
Just test it's work. Hoping help you
var editor_ = CKEDITOR.replace('content', {height: 250});

Resources