Creating a custom Leaflet layer control in React - reactjs

I'm attempting to completely recreate or reorganize the functionality of the LayersControl component in its own separate panel using react-leaflet.
I have several filtered into their own and it works fine, but I'd like to customize the look and location of the Control element.
I've hosted the current version of my Leaflet app on github pages here. You can see the control on the right, which is the basic Leaflet control, but I'd like to the Icon on the left (the layers icon) to accomplish the same thing instead with custom react components.
Just wondering if anyone can point me in the right direction to beginning to accomplish this!
This is my current render for my react-leaflet map:
render() {
const types = [...new Set(data.map(loc => loc.type))];
const group = types.map(type =>
data.filter(loc => loc.type === type)
.map(({id, lat, lng, name}) =>
<LayersControl.Overlay name={startCase(toLower(type))}>
<LayerGroup>
<Marker key={id} position={[lat, lng]} icon=
{locationIcon}>
<Tooltip permanent direction="bottom" opacity={.6}>
{name}
</Tooltip>
</Marker>
</LayerGroup>
</LayersControl.Overlay>
));
return (
<>
<ControlPanel />
<Map
zoomControl={false}
center={this.state.center}
zoom={this.state.zoom}
maxBounds={this.state.maxBounds}
maxZoom={10}
>
<LayersControl>
<TileLayer
url='https://cartocdn-gusc.global.ssl.fastly.net//ramirocartodb/api/v1/map/named/tpl_756aec63_3adb_48b6_9d14_331c6cbc47cf/all/{z}/{x}/{y}.png'
/>
<ZoomControl position="topright" />
{group}
</LayersControl>
</Map>
</>
);
}

So theres still a few bugs in this but i've managed get most of the way (self taught react) using material UI as an example, can be seen in this sandbox link:
https://codesandbox.io/embed/competent-edison-wt5pl?fontsize=14
The general bassis is that we extend MapControl which means we have to define createLeafletElement, this has to return a generic leaflet (not react) control from the original javascript leaflet package. Essentially making a div with the domutil provided by leaflet and then portaling our react components through that div with react portals.
Again with another class extension we extend some of the classes provided by react-leaflet for layers, i pulled it out and just made a generic layer that you could define a group for, that way you could render any layer (polygon, baselayer etc) and specify the group to tell it where to go in the layer control i.e no need for specific components or overlays. As we are extending the class we need implement and pass down the methods we want to use, like addLayer, remove layer etc. During these implementations i've just added them to state to track what layers are active and such.
Not sure if there are better practices throughout everything i've implemented but this is definitely a start, hopefully in the right direction.
Bugs - The first layer in each group won't turn on correctly without the 2nd item ticked, something to do with state i think but didn't have the time to track it down

Thanks Dylan and Peter for this nice React Leaflet custom control approach. I assumed there was still a bug in the toggleLayer function. It's checked multiple checkboxes and the layers won't change properly. So I restructered a little bit and now it should work fine.
toggleLayer = layerInput => {
const { name, group } = layerInput;
let layers = { ...this.state.layers };
layers[group] = layers[group].map(l => {
l.checked = false;
this.removeLayer(l.layer);
if (l.name === name) {
l.checked = !l.checked;
this.props.leaflet.map.addLayer(l.layer);
}
return l;
});
this.setState({
layers
});
};

Just to elaborate on the bug that is mentioned in Dylans answer...
If you have more then one ControlledLayerItem, none items are added to the map until the very last item is checked. To fix this, the toggleLayer method in ControlLayer2.js has to be slightly modified:
toggleLayer = layerInput => {
const { layer, name, checked, group } = layerInput;
let layers = { ...this.state.layers };
layers[group] = layers[group].map(l => {
if (l.name === name) {
l.checked = !l.checked;
l.checked
? this.props.leaflet.map.addLayer(layer)
: this.removeLayer(layer);
}
return l;
});
this.setState({
layers
});
};
Thanks Dylan for the code, it was really helpfull.

Related

Change material of gltf-imported mesh programmatically - react three fiber

I'm currently working at a project with react-three-fiber. I've imported the model with useGLTF from #react-three/drei.
With
const { nodes, materials } = useGLTF('/model.glb');
I access the materials from the glb-file.
To access and manipulate the model I used gltfjsx to generate the model.
Now I need to change the material of a mesh programmatically. Because I have no direct access to the JSX of the model I do it with React.cloneElement and modify the props of the mesh.
So I tried something like this:
return React.cloneElement(mesh, {
material: overwriteMaterial ?
<meshStandardMaterial attach="material" color={0xa3005c} metalness={1} roughness={0.2} visible={true} /> :
materials['mat_7']
});
If overwriteMaterial is false it works. It shows the material it should. But if it's true then the mesh disappears.
I also thought of putting the <meshStandardMaterial /> in the children prop of the mesh. Something like so:
return React.cloneElement(mesh, {
material: overwriteMaterial ? undefined : materials['mat_7'],
children: overwriteMaterial ? <meshStandardMaterial attach="material" color={0xa3005c} metalness={1} roughness={0.2} visible={true} /> : undefined
});
With this I always get this error and I don't know why it appears:
TypeError: Cannot read properties of undefined (reading 'visible')
Could this approach somehow work or am I doing something completely wrong?
Every help is welcome. Thanks
Alright so I found the answer by myself after some more hours searching for a solution.
The material property doesn't accept a JSX-tag. So if you create an instance of the class MeshStandardMaterial you can pass it to the property and it works perfectly fine. Now it looks something like this:
return React.cloneElement(mesh, {
material: overwriteMaterial
? new MeshStandardMaterial({ color: 0x0ff000 })
: materials['mat_7']
})
Note: The class MeshStandardMaterial is exported from the three package.
i really don't think you have to clone any react element, that doesn't seem correct. you can clone or mutate materials just as you would in a plain three app. i have no idea why you even want to clone jsx.
const { scene } = useGLTF(url)
const clonedScene = useMemo(() => scene.clone(), [])
useLayoutEffect(() => {
clonedScene.traverse(o => {
if (o.type === 'Mesh') {
o.material = ...
}
})
}, [clonedScene]}
return <primitive object={clonedScene} />
you can skip the clonedScene thing completely as well, this is only if you plan to re-use the model in your scene multiple times.

How to mange a paste event within CKEdit 5 React component?

When you employ the CKEditor, the user might try to be edgy and paste several thousand lines at once. The browser wouldn't like that. One strategy would be to intercept the paste event and trim the data to a more manageable chunk.
Looking around I found this question - this is basically the same situation, I only can't get my head around how to achieve the same with the React component.
I'd also appreciate different and more insightful strategies.
In short, I posed a question directly in the developer's github issue tracker. With a lot of trail and error in the Javascript console and their eventual answer I managed to control the text coming in the CKEditor with a paste event.
Key points:
I used onInit prop. onReady didn't work for me.
The data in the paste event is divided in elements (like html ones) and is being accessed a bit weirdly.
I guess the best way to explain what I did would be to just show the code, so:
<CKEditor
id={id}
editor={ClassicEditor}
data={value}
onInit={editor => {
const documentView = editor.editing.view.document
documentView.on('paste', (event, data) => {
editor.plugins.get('Clipboard').on('inputTransformation', (event, data) => {
let accumulated = editor.getData()
for (const element of data.content.getChildren()) {
if (element._textData !== undefined) {
accumulated += element._textData
} else {
accumulated += element.getChild(0)._textData
}
if (accumulated.length >= SOME_LENGTH) {
event.stop()
editor.setData('')
editor.setData(accumulated.slice(0, SOME_LENGTH))
break
}
}
})
})
}}
onChange={(event, editor) => {
const data = editor.getData()
inputOnChange(data)
}}
/>
So that's it. I hope this shortens someone else's struggle a bit.

Recording user interactions in React Native / Snap Carousel - firstItem

I have been having this issue for a couple of days and cannot seem to find a solution.
I would like to record the user's interaction on a database. I am displaying data using a React Native Snap Carousel, and need to record if the item was viewed by the user. To do this, and as described in other stack overflow questions, I am using "onSnapToItem". onSnapToItem is triggered everytime I change from one slide to another. Then, if the user views the slide for more than 2 seconds, I count that as an interaction.
The problem is that onSnapToItem is not triggered on the firstItem (which makes sense, because I am not changing slide). Can anybody think of a solution?
<Carousel
vertical
layout={"default"}
ref={_carousel}
data={promos}
renderItem={_renderItem}
autoplay={true}
autoplayInterval={4000}
onSnapToItem = { (index) => {
clearTimeout(writeDelay)
writeDelay=setTimeout (()=>{
console.log(promos[index].id)
},2000)
}}
onEndReached={_retrieveMore}
/>
Programmatically snap to item on screen focus.
componentDidMount() {
setTimeout(() => this._carousel.snapToItem(0), 1000);
// if above code doesn't work then you can try is for first item
writeDelay=setTimeout (()=>{
console.log(promos[0].id); // index here is 0 for first item
},1000)
}
...
render() {
<Carousel
...
ref={c => { this._carousel = c }}
/>
}`
you can use this library #svanboxel/visibility-sensor-react-native

How do I make a selected radio button change one piece of state based upon another radio button changing another piece of state?

I have a couple of components I am building and have run into a bit of a stumbling block.
The components start with a piano keyboard on which I can overlay different musical entities, like notes, intervals, chords, scales, etc...by passing the note names via a notes={[]} array prop into the Keyboard component. In this particular instance of the component I am then importing it into a Scales component in which I have added scale and note buttons, so I can overlay entire scales in this instance on top of the keyboard, which is all basically working. have a list of note names that I can click on and then overlay that scale on top of the keyboard, like so:
The gif shows the current behavior of the Scales component, which is not quite correct yet...
In the gif you can see that the major and minor scale buttons change the state of the scale, which is then used by the note name buttons to change the state of the keyboard beneath it. But what I also want it to do is switch the currently selected scale when the major or minor button is clicked, but currently the note name buttons don't automatically react to the change in state in the major and minor buttons, but have to be clicked again to make the change occur.
What I want is to be able to just click the major and minor buttons and which ever note is selected will simply change from major to minor without having to re-click the selected scale note again, which is the current behavior.
So, in my Scales component I am using custom radio buttons like so, first to control the major and minor buttons:
<MajorInput
type="radio"
name="scale"
id="major"
label="major"
value="major"
checked={scale === 'major'}
onChange={handleChange}
onClick={() => setScale('major')}
/>
<MajorLabel
whileHover={{ scale: 1 }}
whileTap={{ scale: 0.9 }}
htmlFor="major"
>
Major
</MajorLabel>
...then to control the note buttons, like so:
<NoteInput
id="c"
scale={scale}
type="radio"
name="notes"
label="c"
value="c"
onClick={
() => setNotes(
scale === 'major' ? ['c1p', 'd1ma', 'e1ma', 'f1p', 'g1p', 'a1ma', 'b1ma'] :
scale === 'minor' ? ['c1p', 'd1ma', 'eb1mi', 'f1p', 'g1p', 'ab1mi', 'bb1mi'] :
''
)
}
/>
<NoteLabel
whileHover={{ scale: 1 }}
whileTap={{ scale: 0.9 }}
scale={scale}
htmlFor="c"
>
{
scale === 'major' ? 'C' :
scale === 'minor' ? 'C' :
'C'
}
</NoteLabel>
...and the state is established via two useState hooks, like so:
const [ scale, setScale] = useState('')
const [ notes, setNotes] = useState([])
...then ultimately the imported Keyboard component receives it's notes={notes} prop from the notes buttons, like so:
<Keyboard octaves={'2'} notes={notes}/>
...so i don't really know how I could make the note buttons be aware or know about the scale buttons being clicked and then translate that information to the keyboards notes prop, which is where i am stuck now...
Here is a code sandbox of the the component:
https://codesandbox.io/s/scales-981uk
Thank you for your help :-)
I looked through your code.
The problem you have right now is that your note components are not rerendered and restyled when the major button is clicked. In React, you can use the change in props to trigger a rerender which will also restyle your notes.
I would suggest to put all your note inputs into a sub component. :
// ./Scales.js
import NoteButtonBox from ./NoteButtonBox.js
//...
// important: pass scale as props.
// Everytime scale changes, the note buttons are rerendered and restyled
sub component
return (
<Container>
<ScaleButtonBox>
{/* ... */}
<ScaleButtonBox>
<NoteButtonBox scale={scale} />
{/* ... */}
// ./NoteButtonBox.js
const NoteButtonBox = ({scale}) => {
// Don't forget to also move 'const [notes, setNotes] = useState([]);' into the
const [notes, setNotes] = useState([]);
return {
/* return your styled notes based on props scale */
}
}
EDIT
For situations where you need to access state across multiple sub components, you can use React Context. Alternatively, you can use React Redux which accomplishes the same thing. I would suggest Comtext because it is a native part of React.
Breaking up your app into sub components might seem like unnecessary work but it is good practice to create many small components in React. React encourages composition like I suggest.
Create a NotesStateContext class.
You define the where it is needed NotesStateContext.Provider:
<NotesStateContext.Provider value="dark">
<NoteButtonBox />
</* All other components that need to access the state of your notes */>
</NotesStateContext.Provider>
Get and update your state from the provider

React- onClick styling of currentTarget

I am trying to build a simple dynamically updated, interactive list that styles each <li></li> according to the css rules of a .clicked class, when you click on them.
The app is composed of two components, a parent and a child and the code in question is the following (taken from the child):
handleClick(e) {
document.getElementById(e.currentTarget.id).setAttribute("class","clicked");
}
render() {
let ar = this.props.sentences;
let pro = ar.map((x,i)=>{ return (<li id={i} key={i} className={i%2==0 ? "white" : "grey"}
onClick={this.handleClick}>{x}</li>); })
return (
<div>
<ul id="ul">{ pro }</ul>
</div>
What is happening here is basically that the parent is passing to the child a sentences prop (an array of sentences that will form the basis for the formation of a dynamic list).
The controversial part is me using DOM manipulation in the form of document.getElementById(e.currentTarget.id).setAttribute("class","two");
in order to change the class of the dynamically created html from jsx.
The code above works, however it does not feel as best practice. The whole advantage in using react is to use virtual dom and optimize the way the DOM is updated.
My questions are the following:
1) Am I right to feel this way? (that my solution is not best practice?)
2) (If so, ) How can I structure my code in order to use the virtual dom machinery react offers?
If you know this question to be a duplicate, please leave a comment and I ll remove it.
1) Am I right to feel this way? (that my solution is not best practice?)
It is correct to assume that this is not an ideal approach, manipulating the DOM via vanilla js in React has its place (Example Use Cases) but should not be done unless absolutely necessary. Also, it is not ideal to use the index from Array.prototype.map as the key on your components as if they change order it can cause confusion for React as the keys would map differently in that case.
2) (If so, ) How can I structure my code in order to use the virtual dom machinery react offers?
You should make use of the component state. If you want each clicked element to maintain the clicked class then make a piece of state that caches the elements that have already recieved the clicked class. if only the most recently clicked element gets the clicked class then simply cache an identifier to the appropriate element in the state. You could also use refs for this purpose though the overusage of them is somewhat discouraged by facebook.
Here is a quick snipped that will toggle the click class on each <li>
class Test extends Component {
constructor() {
super();
this.state = {
clicked: {}
};
}
render() {
let ar = this.props.sentences;
let pro = ar.map((x, i) => {
const color_class = i % 2 === 0 ? "white" : "grey";
const clicked_class = this.state.clicked[i] === true ? "clicked" : "";
let clicked = Object.assign({}, this.state.clicked); // Dont mutate state!!!
return (
<li
id={i}
key={i}
className={`${color_class} ${clicked_class}`}
onClick={e => {
if (clicked.hasOwnProperty(i)) {
delete clicked[i];
} else {
clicked[i] = true;
}
this.setState({ clicked });
}}
>
{x}
</li>
);
});
return (
<div>
<ul id="ul">
{pro}
</ul>
</div>
);
}
}

Resources